假设我有一个只有2列的MySQL表:
id
invited_by_id
我想知道
每个ID在invited_by_id
列中显示的次数。
如何仅使用一个查询进行此操作?
答案 0 :(得分:7)
GROUP BY
列上的简单invited_by_id
就是您所需要的,因为它与id
列保持相同的ID值:
SELECT invited_by_id, COUNT(*) AS invited_count FROM table GROUP BY invited_by_id
答案 1 :(得分:3)
select id1.id, (count*)
from id as id1
inner join id as id2 on id1.id = id2.invited_by_id
group by id1.id
答案 2 :(得分:1)
select invited_by_id, count(*) from table group by invited_by_id
答案 3 :(得分:1)
SELECT m.id
, grp.cnt
FROM
( SELECT DISTINCT id
FROM mytable
) AS m
LEFT JOIN
( SELECT invited_by_id
, COUNT(*) AS cnt
FROM mytable
GROUP BY invited_by_id
) AS grp
ON grp.invited_by_id = m.id