https://api.drupal.org/api/drupal/includes%21actions.inc/function/actions_do/7.x

addFileds :

这个更全点:

https://www.drupal.org/docs/7/api/database-api/database-api-overview

这个distinct:

https://www.drupal.org/node/706264

//

  1. SELECT COUNT(*) FROM (SELECT DISTINCT first_field, second_field, third_field FROM the_table) AS distinct_three
  2. to work more generally.
  3.  
  4. using DBTNG in Drupal this would look like
  5.  
  6. db_select($table)
  7. ->fields($table, array('field1', 'field2'))
  8. ->distinct()
  9. ->countQuery();

//db_count 方法:

https://www.drupal.org/node/1848376

Count queries

 
Last updated on

5 December 2016
 

Count queries

Any query may have a corresponding "count query". The count query returns the number of rows in the original query. To obtain a count query, use the countQuery() method.

  1. $count_query = $query->countQuery();
  2. $count_query is now a new Dynamic Select query with no ordering restrictions that when executed will return a result set with only one value, the number of records that would be matched by the original query. Because PHP supports chaining methods on returned objects, the following idiom is a common approach:
  3.  
  4. $num_rows = $query->countQuery()->execute()->fetchField(); //输出数量
  5.  
  6. $detail_r = $detailresult->fetchAssoc();
  7. $detailresult->rowCount()
  1.  

db_select 方法:

https://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7.x

https://api.drupal.org/api/drupal/includes%21database%21database.inc/7.x

  1. https://api.drupal.org/api/drupal/includes%21database%21select.inc/class/SelectQueryExtender/7.x

简单截图:

  1.  

// db_select :subQuery :

if you need joining a

ParisLiakos commented 6 years ago

if you need joining a subquery use this:

  1. // Create a subquery, which is just a normal query object.
  2. $subquery = db_select('test_task', 'tt');
  3. $subquery->addField('tt', 'pid', 'pid');
  4. $subquery->condition('priority', );
  5.  
  6. // Create another query that joins against the virtual table resulting
  7. // from the subquery.
  8. $select = db_select('test', 't');
  9. $select->join($subquery, 'tt', 't.id=tt.pid');
  10. $select->addField('t', 'name');
  11.  
  12. // The resulting query should be equivalent to:
  13. // SELECT t.name
  14. // FROM test t
  15. // INNER JOIN (SELECT tt.pid AS pid FROM test_task tt WHERE priority=1) tt ON t.id=tt.pid
  1.  
  1. // db_query
  1. $result = db_query('SELECT n.nid, n.title, n.created
  2. FROM {node} n WHERE n.uid = :uid AND n.type = :type', array(':uid' => $uid, ':type' => 'page'));
  3. // Result is returned as a iterable object that returns a stdClass object on each iteration
  4. foreach ($result as $record) {
  5. // Perform operations on $record->title, etc. here.
  6.  
  7. print($record->title . "");
  8.  
  9. // in this example the available data would be mapped to object properties:
  10. // $record->nid, $record->title, $record->created
  11. }
  1. //date_format:
  1. $sql = "SELECT (DATE_FORMAT(FROM_UNIXTIME(co.changed), '%d-%m-%Y')) AS date, ci.type AS type, co.status, COUNT(distinct(co.order_id)) AS count
  2. FROM commerce_order co
  3. LEFT JOIN commerce_line_item ci ON co.order_id = ci.order_id
  4. GROUP BY date, co.status, ci.type
  5. ORDER BY date";
  6. $result = db_query($sql);
  7. foreach ($result as $row) {
  8. print_r($row);
  9. }

  1. //Left Join SubQuery
  1. Query I am executing with db_select:
  2.  
  3. $query = db_select('node_view_count', 'n');
  4. $query->join('users', 'u', 'n.uid = u.uid'); //JOIN node with users
  5.  
  6. $query->groupBy('n.nid');//GROUP BY user ID
  7. $query->groupBy('u.name');//GROUP BY user ID
  8.  
  9. $query->fields('n',array('nid'))//SELECT the fields from node_view_count
  10. ->fields('u',array('name'))//SELECT the fields from user
  11. ->condition('n.uid','','<>')
  12. ->orderBy('timestamp', 'DESC');//ORDER BY created
  1. 2\
  1. $connection = Database::getConnection();
  2. $sth = $connection->select('file_managed', 'fm');
  3. $sth->addField('fm', 'filemime');
  4. $sth->addExpression('COUNT(fm.filemime)', 'count');
  5. $sth->groupBy('fm.filemime');
  6. // Execute the statement
  7. $data = $sth->execute();
  8. // Get all the results
  9. $results = $data->fetchAll(\PDO::FETCH_ASSOC);
  1. //结果集处理:
  1. db_like($prefix);
  1. https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_like/7.x
  1. $search_string ="per";
  2. $result = db_query('SELECT title
  3. FROM {node} n
  4. WHERE n.title like :title'
  5. ,array(':title' => "%".$search_string."%"))
  6. ->fetchAll();
  7. print_r($result);
  8.  
  9. $result = db_select('person', 'p')
  10. ->fields('p')
  11. ->condition('name', db_like($prefix) . '%', 'LIKE')
  12. ->execute()
  13. ->fetchAll();
  1. $sql = 'SELECT sid, score FROM {search_index} WHERE word LIKE :term';
  2. $result = db_query($sql, array(':term' => '%' . db_like($search_term)));

  1. //结果集处理:
  1. <?php
  2. // Using the same query from above...
  3. $uid = ;
  4. $result = db_query('SELECT n.nid, n.title, n.created
  5. FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
  6.  
  7. // Fetch next row as a stdClass object.
  8. $record = $result->fetchObject();
  9.  
  10. // Fetch next row as an associative array.
  11. $record = $result->fetchAssoc();
  12.  
  13. // Fetch data from specific column from next row
  14. // Defaults to first column if not specified as argument
  15. $data = $result->fetchColumn(); // Grabs the title from the next row
  16.  
  17. // Retrieve all records into an indexed array of stdClass objects.
  18. $result->fetchAll();
  19.  
  20. // Retrieve all records as stdObjects into an associative array
  21. // keyed by the field in the result specified.
  22. // (in this example, the title of the node)
  23. $result->fetchAllAssoc('title');
  24.  
  25. // Retrieve a 2-column result set as an associative array of field 1 => field 2.
  26. $result->fetchAllKeyed();
  27. // Also good to note that you can specify which two fields to use
  28. // by specifying the column numbers for each field
  29. $result->fetchAllKeyed(,); // would be nid => created
  30. $result->fetchAllKeyed(,); // would be title => nid
  31.  
  32. // Retrieve a 1-column result set as one single array.
  33. $result->fetchCol();
  34. // Column number can be specified otherwise defaults to first column
  35. $result->fetchCol($db_column_number);
  36.  
  37. // Count the number of rows
  38. $result->rowCount();
  39. //count just one
  40. $dev_query = "select id from aa where ont > UNIX_TIMESTAMP() - 60 group by id";
  41. $id = db_query($dev_query)->fetchField(); //print only one id string
  42. $a = ;
  43.  
  44. ?>
  1. //DB_insert
    https://www.drupal.org/node/310079
  2.  
  3. https://dev.mysql.com/doc/refman/5.7/en/insert-select.html //db insert 语法
  1. //多条数据的插入
  1. $values = array(
  2. array(
  3. 'title' => 'Example',
  4. 'uid' => ,
  5. 'created' => REQUEST_TIME,
  6. ),
  7. array(
  8. 'title' => 'Example 2',
  9. 'uid' => ,
  10. 'created' => REQUEST_TIME,
  11. ),
  12. array(
  13. 'title' => 'Example 3',
  14. 'uid' => ,
  15. 'created' => REQUEST_TIME,
  16. ),
  17. );
  18. $query = db_insert('node')->fields(array('title', 'uid', 'created'));
  19. foreach ($values as $record) {
  20. $query->values($record);
  21. }
  22. $query->execute();

  1. //基于select的插入:
  1. <?php
  2. // Build the SELECT query.
  3. $query = db_select('node', 'n');
  4. // Join to the users table.
  5. $query->join('users', 'u', 'n.uid = u.uid');
  6. // Add the fields we want.
  7. $query->addField('n','nid');
  8. $query->addField('u','name');
  9. // Add a condition to only get page nodes.
  10. $query->condition('type', 'page');
  11.  
  12. // Perform the insert.
  13. db_insert('mytable')
  14. ->from($query)
  15. ->execute();
  16. ?>
  1.  
    db_insert 模拟 insert ignore 参数:
    https://drupal.stackexchange.com/questions/89253/how-to-set-insert-ignore-in-db-insert-without-db-merge (

How to set 'INSERT IGNORE' in db_insert without db_merge

  1. 貌似不可实现)
    解决方案:
  1. 1
  1. try {
  2. $insertID = db_insert('crawl_data')->fields(array(
  3. 'url' => $url,
  4. ))->execute();
  5. } catch (Exception $ex) {
  6. //这样就不会执行插入,并且不报错...
  7. }
  1. 2):先查一下,再入库
    其他:
  1. db_merge('people')
  2. ->key(array('job' => 'Speaker'))
  3. ->insertFields(array('age' => ,'name' => 'Meredith'))
  4. ->updateFields(array('name' => 'Tiffany'))
  5. ->execute();

//如果存在job为Speaker的一条记录,则更新name为Tiffany,如果不存在,就插入一条age为31,name为Meredith,job为Speaker的记录。

6.对数据库某字段值自动加一或者自增。

复制代码 代码如下:

  1. db_update('example_table')
  2. ->expression('count', 'count + 1')
  3. ->condition('field1', $some_value)
  4. ->expression('field2', 'field2 + :inc', array(':inc' => ))
  5. ->execute();

//通过子sql查询插入

  1. <?php
  2. // Build the SELECT query.
  3. $query = db_select('node', 'n');
  4. // Join to the users table.
  5. $query->join('users', 'u', 'n.uid = u.uid');
  6. // Add the fields we want.
  7. $query->addField('n','nid');
  8. $query->addField('u','name');
  9. // Add a condition to only get page nodes.
  10. $query->condition('type', 'page');
  11.  
  12. // Perform the insert.
  13. db_insert('mytable')
  14. ->from($query)
  15. ->execute();
  16. ?>
  1. https://api.drupal.org/api/drupal/includes%21database%21database.inc/7.x
  2.  
  1. //DB_AND || DB_OR
  1. $and = db_and()->condition('mid', )->condition('cache_type', 'year');
  2. $and = db_or()->condition('mid', )->condition('cache_type', 'year');
  3. $query->condition($or);
  1. //切换数据库
  1. // set external database.
  1. db_set_active('panel');
  2. // Start select query.
  3. $query = db_select('gw_route', 'g');
  4. $query->fields('g', array('country', 'cost'));
  5.  
  6. // Create expression (acts the same as any db value at sql) and use it.
  7. $query->addExpression('MIN(g.cost)', 'min_cost');
  8.  
  9. $query->condition('g.country', '','!=');
  10. $query->groupBy('g.country');
  11. $query->orderBy('g.country', 'ASC');
  12. $result = $query->execute();
  13. // Set active default database.
  14. db_set_active();
  15. while($record = $result->fetchAssoc()) {
  16. print_r($record);
  17. }
  1.  
  1. //LEFT_JOIN 子查询 sub_query
    原理(code):
  1. public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
  2. return $this->addJoin('LEFT OUTER', $table, $alias, $condition, $arguments);
  3. }
  4. //add join
  5. public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = array()) {
  6.  
  7. if (empty($alias)) {
  8. if ($table instanceof SelectQueryInterface) {
  9. $alias = 'subquery';
  10. }
  11. else {
  12. $alias = $table;
  13. }
  14. }//对table 做了是否是查询的判断
  15.  
  16. $alias_candidate = $alias;
  17. $count = ;
  18. while (!empty($this->tables[$alias_candidate])) {
  19. $alias_candidate = $alias . '_' . $count++;
  20. }
  21. $alias = $alias_candidate;
  22.  
  23. if (is_string($condition)) {
  24. $condition = str_replace('%alias', $alias, $condition);
  25. }
  26.  
  27. $this->tables[$alias] = array(
  28. 'join type' => $type,
  29. 'table' => $table,
  30. 'alias' => $alias,
  31. 'condition' => $condition,
  32. 'arguments' => $arguments,
  33. );
  34.  
  35. return $alias;
  36. }
  37.  
  38. QQQQ:

How to set an alias to a fields on a db_select?

  1.  
  1. $query = db_select('super_long_table', 'slt');
  2. $query->addField('slt', 'mys_super_long_field', 'mslf');
  1.  
  1.  
  1.  

drupal 用法小结,drupal select ,query ,distinct的更多相关文章

  1. mysql 去除重复 Select中DISTINCT关键字的用法 在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是 distinct只能返回它的目标字段,而无法返回其它字段,这个问题让我困扰了很久,用distinct不能解决的话,

      在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供 有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记 ...

  2. Delphi中ClientDataSet的用法小结

    Delphi中ClientDataSet的用法小结 TClientDataSet控件继承自TDataSet,其数据存储文件格式扩展名为 .cds,是基于文件型数据存储和操作的控件.该控件封装了对数据进 ...

  3. 1:CSS中一些@规则的用法小结 2: @media用法详解

    第一篇文章:@用法小结 第二篇文章:@media用法 第一篇文章:@用法小结 这篇文章主要介绍了CSS中一些@规则的用法小结,是CSS入门学习中的基础知识,需要的朋友可以参考下     at-rule ...

  4. MVC图片上传详解 IIS (安装SSL证书后) 实现 HTTP 自动跳转到 HTTPS C#中Enum用法小结 表达式目录树 “村长”教你测试用例 引用provinces.js的三级联动

    MVC图片上传详解   MVC图片上传--控制器方法 新建一个控制器命名为File,定义一个Img方法 [HttpPost]public ActionResult Img(HttpPostedFile ...

  5. hive中select中DISTINCT的技巧和使用

    hive中select中DISTINCT的技巧和使用 单表的唯一查询用:distinct 多表的唯一查询用:group by 在使用MySQL时,有时需要查询出某个字段不重复的记录,虽然mysql提供 ...

  6. 转载:Hadoop排序工具用法小结

    本文转载自Silhouette的文章,原文地址:http://www.dreamingfish123.info/?p=1102 Hadoop排序工具用法小结 发表于 2014 年 8 月 25 日 由 ...

  7. [No000010]Ruby 中一些百分号(%)的用法小结

    #Ruby 中一些百分号(%)的用法小结 #这篇文章主要介绍了Ruby 中一些百分号(%)的用法小结,需要的朋友可以参考下 what_frank_said = "Hello!"#% ...

  8. C++ typedef用法小结 (※不能不看※)

    C++ typedef用法小结 (※不能不看※) 第一.四个用途 用途一: 定义一种类型的别名,而不只是简单的宏替换.可以用作同时声明指针型的多个对象.比如:char* pa, pb; // 这多数不 ...

  9. 函数fgets和fputs、fread和fwrite、fscanf和fprintf用法小结 (转)

    函数fgets和fputs.fread和fwrite.fscanf和fprintf用法小结 字符串读写函数fgets和fputs 一.读字符串函数fgets函数的功能是从指定的文件中读一个字符串到字符 ...

随机推荐

  1. debian下配置keepalived ha

    抄袭自http://blog.51yip.com/server/1417.html,做了一些修改 可以参考http://blog.linuxphp.org/archives/1615/ 备注:NAT模 ...

  2. PHP中imagecopyresampled参数详解

    原文链接http://blog.csdn.net/ajaxchen_615/article/details/5941181 做php缩微图程序,用到了imagecopyresampled函数,在网上找 ...

  3. Hadoop专业解决方案-第12章 为Hadoop应用构建企业级的安全解决方案

    一.前言: 非常感谢Hadoop专业解决方案群:313702010,兄弟们的大力支持,在此说一声辛苦了,春节期间,项目进度有所延迟,不过元宵节以后大家已经步入正轨, 目前第12章 为Hadoop应用构 ...

  4. bzoj 1414: [ZJOI2009]对称的正方形

    Description Orez很喜欢搜集一些神秘的数据,并经常把它们排成一个矩阵进行研究.最近,Orez又得到了一些数据,并已经把它们排成了一个n行m列的矩阵.通过观察,Orez发现这些数据蕴涵了一 ...

  5. 学习笔记之REST/RESTful

    REST(Representational state transfer) - Wikipedia https://en.wikipedia.org/wiki/Representational_sta ...

  6. storm的代码实现

    先模拟产生一些数据 我把这些数据摘一部分下来 2017-06-10 18:25:56,092 [main] [org.apache.kafka.common.utils.AppInfoParser] ...

  7. jQuery更新

    jQuery jQuery介绍 jQuery是一个轻量级的.兼容多浏览器的JavaScript库. jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方便地进行 ...

  8. svn+apache+ssl快速部署

    在svn+apache文章中已经成功搭建了web-svn,由于在http网络上数据都是以明文传输,公司的源码需要一定的保密机制,基于安全考虑现整合web-svn+ssl.构建安全的svn服务器, 1. ...

  9. 用python登录远程salt,并执行命令

    用python操作saltstack,如果是在本地,则可以用python的salt模块,但如果要操作远程saltstack,则不行,今天就来看看怎么操作. 用python操作远程的saltstack, ...

  10. jqgird

    将jqgird某字段设为超链接,并传递相关参数 cellvalue:为后台传递过来的字段数据 rowObject:为本行数据 实现: formatter:function(cellvalue, opt ...