我有两张桌子:
表_1 表_2
uid | eid | cid cid | eid | name
---------------- ----------------
20 | 1 | 3 1 | 1 | Amy
20 | 1 | 2 2 | 1 | Sam
20 | 1 | 3 3 | 1 | Paul
20 | 2 | 1 4 | 2 | June
20 | 2 | 2 5 | 2 | Peter
20 | 2 | 2 6 | 2 | Mary
我需要以下结果:
name | number
--------------
Amy | 0
Sam | 1
Paul | 2
我的代码是
select t2.`name` , t2.cid, a.number from table_2 t2
left join table_1 t1 on t2.eid = t1.eid
left join (select t12.cid, count(t12.cid) as number from table_1 t12
inner join table_2 t22
where t12.eid = 1 and t12.cid = t22.id group by t12.eid)a on t2.id = a.cid
where t1.eid = 1 group by t2.id
我得到的是
name | number
--------------
Amy | null
Sam | 1
Paul | 2
如果我使用它不起作用
IFNULL(count(t12.cid),0)
有什么建议么?