Heim  >  Artikel  >  Backend-Entwicklung  >  mysql - 怎么用thinkphp的查询语言构建这样的select查询?

mysql - 怎么用thinkphp的查询语言构建这样的select查询?

WBOY
WBOYOriginal
2016-06-06 20:32:281130Durchsuche

求助如何用thinkphp的查询语言做到下面这样的查询。。

table a (分类表)
id name
1 l
2 ll
3 lll

table b (内容表)
id cid xname
1 2  x
2 1  xx
3 2  xxx
4 1  xxxxx
5 1  xxxxxxx

<code>select a.id,a.name,(select count(id) as counts from b where b.cid=a.id) from a
//查询分类下的项目数,没有的显示0,及分类id,名称
</code>

return :
id  name  counts
1  l     3
2  ll     2
3  lll     0

回复内容:

求助如何用thinkphp的查询语言做到下面这样的查询。。

table a (分类表)
id name
1 l
2 ll
3 lll

table b (内容表)
id cid xname
1 2  x
2 1  xx
3 2  xxx
4 1  xxxxx
5 1  xxxxxxx

<code>select a.id,a.name,(select count(id) as counts from b where b.cid=a.id) from a
//查询分类下的项目数,没有的显示0,及分类id,名称
</code>

return :
id  name  counts
1  l     3
2  ll     2
3  lll     0

$Model = M('A');
$Model->field('a.id,a.name,count(a.id)')->join('LEFT JOIN B ON A.id = B.cid')->group(a.id)->select();

使用虚拟模型 进行多表查询

//$table['表'] = 别名
$table['a'] = a;//a表
$thble['b'] = b;//b表
$this->Table($table)->Where('b.cid = a.id')->getfield('a.id,a.name,count(b.id) as counts');

<code>SELECT a.id, a.name, COUNT(b.id) AS row_number FROM a LEFT JOIN b ON a.id = b.cid GROUP BY a.id;
</code>

重点在:GROUP BY a.id

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn