Home > Backend Development > PHP Tutorial > ThinkPHP 多表查询-如其字段A相同,则把字段B相加

ThinkPHP 多表查询-如其字段A相同,则把字段B相加

WBOY
Release: 2016-06-13 12:01:45
Original
1257 people have browsed it

ThinkPHP 多表查询-如果字段A相同,则把字段B相加

在一个项目中,需要查询表tr_product中的user_id字段,如果user_id相同,则把其对应的money字段相加,数据库截图如下:

实现代码:

$Model = D('Model');
$res =$Model->query("SELECT user_id,sum(money) from tr_order GROUP BY user_id");

结果:

array (size=2)
  0 =>
    array (size=2)
      'user_id' => string '72' (length=2)
      'sum(money)' => string '100677.00' (length=9)
  1 =>
    array (size=2)
      'user_id' => string '89' (length=2)
      'sum(money)' => string '34.00' (length=5)

 

技术扩展:

使用ThinkPHP提供的query函数,能够直接输入我们的sql语句。

GROUP BY 按user_id分组。

sum()函数:并对的money字段值进行累加。

A PHPer and a Linuxer
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template