求助如何用thinkphp的查询语言做到下面这样的查询。。
table a (分类表)
id name
1 l
2 ll
3 lll
table b (内容表)
id cid xname
1 2x
2 1xx
3 2xxx
4 1xxxxx
5 1xxxxxxx
select a.id,a.name,(select count(id) as counts from b where b.cid=a.id) from a//查询分类下的项目数,没有的显示0,及分类id,名称
return :
idnamecounts
1l 3
2ll 2
3lll 0
回复内容: 求助如何用thinkphp的查询语言做到下面这样的查询。。
table a (分类表)
id name
1 l
2 ll
3 lll
table b (内容表)
id cid xname
1 2x
2 1xx
3 2xxx
4 1xxxxx
5 1xxxxxxx
select a.id,a.name,(select count(id) as counts from b where b.cid=a.id) from a//查询分类下的项目数,没有的显示0,及分类id,名称
return :
idnamecounts
1l 3
2ll 2
3lll 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');
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;
重点在:group by a.id