2011-06-24 127 views
1

假設我有一個MySQL表只有兩列:一個SQL查詢,而不是許多

id 
invited_by_id 

,我想知道 有多少次出現在invited_by_id列每個ID。

如何使這隻使用一個查詢?

回答

7

一個簡單的invited_by_idGROUP BY是你所需要的,因爲它擁有相同的ID值作爲id柱:

SELECT invited_by_id, COUNT(*) AS invited_count FROM table GROUP BY invited_by_id 
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 
+0

邁克爾的是更有效的,除非你有擔心invite_by_id中不在id中的值。 – therealmitchconnors

1
select invited_by_id, count(*) from table group by invited_by_id 
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