假設號碼列表是一組您感興趣的朋友(倒不如將它們存儲在一個表中 - 這就是你如何在數據庫中記錄的信息),則:
SELECT e.id, e.name, COUNT(*) AS friends
FROM attendance AS a
JOIN event AS e ON a.event = e.id
WHERE a.user IN (1,2,3,4,5,6,7,8,9,10,11,12,13,444,153)
GROUP BY e.id, e.name;
複雜性,當然,是在旁觀者的眼睛 - 這實際上不是複雜。請注意,正如所寫的,它沒有列出沒有任何朋友去往的事件。如果你想要的,你需要一個LEFT OUTER JOIN和你所需要的「朋友過濾器」比主WHERE子句前面:
SELECT e.id, e.name, COUNT(user) AS friends
FROM event AS e
LEFT OUTER JOIN
(SELECT user, event
FROM attendance
WHERE user IN (1,2,3,4,5,6,7,8,9,10,11,12,13,444,153)
) AS a
ON a.event = e.id
GROUP BY e.id, e.name;
的COUNT(用戶)合計返回零如果一個組中的所有行包含NULL在用戶列中。
未經測試的SQL。
工作perefectly ..謝謝! – Amir 2011-01-22 15:18:11