我有两个表组和联系人,我在联系表中获取所有组的联系人总数。就像在组表中一样,我有值
group1
group2
在联系表中我有
myname group1
myname1 group1
myname2 group1
现在我想要所有的groupname与他们的联系人数量
group1 3
group2 0
我用过:
SELECT g.gid,g.groupname,g.TYPE,g.DATE,COUNT(*)AS cnt,1
FROM groupname g,contacts c
WHERE g.gid=c.gid AND uid=1 GROUP BY groupname
但我得到了那些有价值的团体。
答案 0 :(得分:1)
使用Left Outer Join
代替旧版Inner Join
SELECT g.groupname,
Count(c.gid) as Cnt
FROM groups g
LEFT OUTER JOIN contact c
ON g.gid = c.gid
WHERE uid = 1
GROUP BY g.groupname
答案 1 :(得分:1)
您可以使用相关的子查询:
SELECT g.gid, g.groupname, g.TYPE,
(SELECT COUNT(*)
FROM contacts c
WHERE c.gid = g.gid) AS cnt
FROM groupname g
WHERE uid=1
答案 2 :(得分:0)
SELECT g.gid,g.groupname,g.TYPE,g.DATE,COUNT(*)AS cnt,1
FROM groupname g
LEFT JOIN contacts c on c.group_name = g.group_name
WHERE g.gid=c.gid AND uid=1 GROUP BY groupname