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

//

SELECT COUNT(*) FROM (SELECT DISTINCT first_field, second_field, third_field FROM the_table)  AS distinct_three
to work more generally. using DBTNG in Drupal this would look like db_select($table)
->fields($table, array('field1', 'field2'))
->distinct()
->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.

$count_query = $query->countQuery();
$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: $num_rows = $query->countQuery()->execute()->fetchField(); //输出数量 $detail_r = $detailresult->fetchAssoc();
$detailresult->rowCount()
 

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

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

简单截图:


// db_select :subQuery :

if you need joining a

ParisLiakos commented 6 years ago

if you need joining a subquery use this:

  // Create a subquery, which is just a normal query object.
$subquery = db_select('test_task', 'tt');
$subquery->addField('tt', 'pid', 'pid');
$subquery->condition('priority', ); // Create another query that joins against the virtual table resulting
// from the subquery.
$select = db_select('test', 't');
$select->join($subquery, 'tt', 't.id=tt.pid');
$select->addField('t', 'name'); // The resulting query should be equivalent to:
// SELECT t.name
// FROM test t
// INNER JOIN (SELECT tt.pid AS pid FROM test_task tt WHERE priority=1) tt ON t.id=tt.pid
 
// db_query
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid AND n.type = :type', array(':uid' => $uid, ':type' => 'page'));
// Result is returned as a iterable object that returns a stdClass object on each iteration
foreach ($result as $record) {
// Perform operations on $record->title, etc. here. print($record->title . ""); // in this example the available data would be mapped to object properties:
// $record->nid, $record->title, $record->created
}
//date_format:
 $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
FROM commerce_order co
LEFT JOIN commerce_line_item ci ON co.order_id = ci.order_id
GROUP BY date, co.status, ci.type
ORDER BY date";
$result = db_query($sql);
foreach ($result as $row) {
print_r($row);
}

//Left Join SubQuery
Query I am executing with db_select:

     $query = db_select('node_view_count', 'n');
$query->join('users', 'u', 'n.uid = u.uid'); //JOIN node with users $query->groupBy('n.nid');//GROUP BY user ID
$query->groupBy('u.name');//GROUP BY user ID $query->fields('n',array('nid'))//SELECT the fields from node_view_count
->fields('u',array('name'))//SELECT the fields from user
->condition('n.uid','','<>')
->orderBy('timestamp', 'DESC');//ORDER BY created
2\
$connection = Database::getConnection();
$sth = $connection->select('file_managed', 'fm');
$sth->addField('fm', 'filemime');
$sth->addExpression('COUNT(fm.filemime)', 'count');
$sth->groupBy('fm.filemime');
// Execute the statement
$data = $sth->execute();
// Get all the results
$results = $data->fetchAll(\PDO::FETCH_ASSOC);


//结果集处理:
db_like($prefix);
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_like/7.x
  $search_string ="per";
$result = db_query('SELECT title
FROM {node} n
WHERE n.title like :title'
,array(':title' => "%".$search_string."%"))
->fetchAll();
print_r($result); $result = db_select('person', 'p')
->fields('p')
->condition('name', db_like($prefix) . '%', 'LIKE')
->execute()
->fetchAll();
 $sql = 'SELECT sid, score FROM {search_index} WHERE word LIKE :term';
$result = db_query($sql, array(':term' => '%' . db_like($search_term)));

//结果集处理:
<?php
// Using the same query from above...
$uid = ;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid)); // Fetch next row as a stdClass object.
$record = $result->fetchObject(); // Fetch next row as an associative array.
$record = $result->fetchAssoc(); // Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(); // Grabs the title from the next row // Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll(); // Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title'); // Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(,); // would be nid => created
$result->fetchAllKeyed(,); // would be title => nid // Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number); // Count the number of rows
$result->rowCount();
//count just one
$dev_query = "select id from aa where ont > UNIX_TIMESTAMP() - 60 group by id";
$id = db_query($dev_query)->fetchField(); //print only one id string
$a = ; ?>
//DB_insert
https://www.drupal.org/node/310079 https://dev.mysql.com/doc/refman/5.7/en/insert-select.html //db insert 语法
//多条数据的插入
 $values = array(
array(
'title' => 'Example',
'uid' => ,
'created' => REQUEST_TIME,
),
array(
'title' => 'Example 2',
'uid' => ,
'created' => REQUEST_TIME,
),
array(
'title' => 'Example 3',
'uid' => ,
'created' => REQUEST_TIME,
),
);
$query = db_insert('node')->fields(array('title', 'uid', 'created'));
foreach ($values as $record) {
$query->values($record);
}
$query->execute();

//基于select的插入:
<?php
// Build the SELECT query.
$query = db_select('node', 'n');
// Join to the users table.
$query->join('users', 'u', 'n.uid = u.uid');
// Add the fields we want.
$query->addField('n','nid');
$query->addField('u','name');
// Add a condition to only get page nodes.
$query->condition('type', 'page'); // Perform the insert.
db_insert('mytable')
->from($query)
->execute();
?>
 
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)
try {
$insertID = db_insert('crawl_data')->fields(array(
'url' => $url,
))->execute();
} catch (Exception $ex) {
//这样就不会执行插入,并且不报错...
}
(2):先查一下,再入库
其他:
db_merge('people')
->key(array('job' => 'Speaker'))
->insertFields(array('age' => ,'name' => 'Meredith'))
->updateFields(array('name' => 'Tiffany'))
->execute();

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

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

复制代码 代码如下:

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

//通过子sql查询插入

<?php
// Build the SELECT query.
$query = db_select('node', 'n');
// Join to the users table.
$query->join('users', 'u', 'n.uid = u.uid');
// Add the fields we want.
$query->addField('n','nid');
$query->addField('u','name');
// Add a condition to only get page nodes.
$query->condition('type', 'page'); // Perform the insert.
db_insert('mytable')
->from($query)
->execute();
?>
https://api.drupal.org/api/drupal/includes%21database%21database.inc/7.x

//DB_AND  || DB_OR
$and = db_and()->condition('mid', )->condition('cache_type', 'year');
$and = db_or()->condition('mid', )->condition('cache_type', 'year');
$query->condition($or);
//切换数据库
// set external database.
db_set_active('panel');
// Start select query.
$query = db_select('gw_route', 'g');
$query->fields('g', array('country', 'cost')); // Create expression (acts the same as any db value at sql) and use it.
$query->addExpression('MIN(g.cost)', 'min_cost'); $query->condition('g.country', '','!=');
$query->groupBy('g.country');
$query->orderBy('g.country', 'ASC');
$result = $query->execute();
// Set active default database.
db_set_active();
while($record = $result->fetchAssoc()) {
print_r($record);
}
 
//LEFT_JOIN 子查询 sub_query
原理(code):
public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = array()) {
return $this->addJoin('LEFT OUTER', $table, $alias, $condition, $arguments);
}
//add join
public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = array()) { if (empty($alias)) {
if ($table instanceof SelectQueryInterface) {
$alias = 'subquery';
}
else {
$alias = $table;
}
}//对table 做了是否是查询的判断 $alias_candidate = $alias;
$count = ;
while (!empty($this->tables[$alias_candidate])) {
$alias_candidate = $alias . '_' . $count++;
}
$alias = $alias_candidate; if (is_string($condition)) {
$condition = str_replace('%alias', $alias, $condition);
} $this->tables[$alias] = array(
'join type' => $type,
'table' => $table,
'alias' => $alias,
'condition' => $condition,
'arguments' => $arguments,
); return $alias;
} QQQQ:

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


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

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. 详细说明 配置 Sublime Text 开发node.js(windows)包括sub2和sub3的区别

    1.先安装Sublime Text  2或者3皆可 2.下载 sublime Text 的nodejs插件 得到那个zip包(后面会介绍用Package Control安装) 3.下载后解压 直接改名 ...

  2. Maven基本使用

    Maven基本使用 一.安装 先去官网下载maven(http://maven.apache.org/download.cgi) 下载下来解压后如下所示  配置环境变量   查看配置成功与否  mav ...

  3. phonegap 2.9 IOS Xcode 搭建环境

    一:下载phoneGap2.9和安装Xcode5(目前最新版) 选择2.9是因为3.0以上坑爹版本编译神马的要在有网络情况. 二: 下载phonegap后解压到你的指定文件夹中,解压后找到create ...

  4. bzoj 4927: 第一题

    Description 给定n根直的木棍,要从中选出6根木棍,满足:能用这6根木棍拼 出一个正方形.注意木棍不能弯折.问方案数. 正方形:四条边都相等.四个角都是直角的四边形. Input 第一行一个 ...

  5. autoit 中文API

    中文API 参考地址: http://www.jb51.net/shouce/autoit/ 虫师的selelnium里面也有简单的说 环境搭建+上传弹窗的小案例

  6. 发布程序时出现“类型ASP.global_asax同时存在于...”错误的解决办法

    web程序发布后,通过浏览器访问程序显示如下的错误信息: 编译器错误消息: CS0433: 类型“ASP.global_asax”同时存在于“c:\WINDOWS\Microsoft.NET\Fram ...

  7. [转]Excel.dll 导出Excel控制

    Excel.dll 导出Excel控制 2010-06-12 11:26 2932人阅读 评论(2) 收藏 举报 excelmicrosoftstring产品服务器google 最近做了个导出Exce ...

  8. 帆软报表平台FineReport

    报表软件FineReport使用方法 一种方法是从FineReport报表软件中进入:打开设计器,选择“服务器”,点击“报表平台管理”,即可进入.用户首次进入报表平台,系统会要求填写管理员的账户和密码 ...

  9. tomcat 性能优化(内存优化 线程优化)

    转自:http://blog.sina.com.cn/s/blog_4b5bc01101014s81.html tomcat 性能优化 linux修改TOMCAT_HOME/bin/catalina. ...

  10. ElasticSearch client API

    从运行结果看并没有打印节点信息出来 从结果看出来,集群节点信道打印出来了,不过这种方法有个问题,就是当我们连接的节点挂掉了,就没法连接整个集群了,这个时候我们就利用他的一个嗅探的功能. 从这里我们可以 ...