3

我有看起来像这样的 SQL 数据

events
id name         capacity
1  Cooking        10
2  Swimming       20
3  Archery        15

registrants
id  name
1   Jimmy
2   Billy
3   Sally

registrant_event
registrant_id  event_id
     1             3
     2             3
     3             2

我想选择“事件”中的所有字段以及一个附加字段,即当前注册该事件的人数。在这种情况下,Archery 将有 2 个注册者,Swimming 将有 1 个,Cooking 将有 0 个。

我想这可以在单个查询中完成,但我不确定正确的语法。如何编写查询来获取该数据?

更新:感谢您的精彩回答,你们都摇滚!

4

7 回答 7

10
SELECT e.*, ISNULL(ec.TotalRegistrants, 0) FROM events e LEFT OUTER JOIN
(
   SELECT event_id, Count(registrant_id) AS TotalRegistrants
   FROM registrant_event
   GROUP BY event_id
) ec ON e.id  = ec.event_id
于 2008-10-15T19:11:31.403 回答
2
SELECT Events.ID, Events.Name, Events.Capacity, 
       ISNULL(COUNT(Registrant_Event.Registrant_ID), 0)
FROM Events
LEFT OUTER JOIN Registrant_Event ON Events.ID = Registrant_Event.Event_ID
GROUP BY Events.ID, Events.Name, Events.Capacity
于 2008-10-15T19:14:48.430 回答
1
select d.id1, d.name, d.cappacity, count(d.b_id) as number_of_people
from (select eve.id1,eve.name,eve.cappacity,re_eve.b_id
     from eve left join re_eve on eve.id1 = re_eve.b_id) d
group by d.id1, d.name, d.cappacity
于 2011-02-22T06:42:51.127 回答
0
select e.id, e.name, e.capacity, IsNull(re.eventCount,0) from events e
left join (
 select count(event_id) as eventCount, event_id  from registrant_event group by event_id
 ) re 
on e.id = re.event_id
于 2008-10-15T19:15:10.880 回答
0

我在 Oracle 11g 中对此进行了测试,它似乎可以工作

SELECT e.id, e.name, e.capacity, COUNT(re.event_id)
FROM events e
LEFT JOIN registrant_event re
  ON e.id = re.event_id
GROUP BY e.id, e.name, e.capacity
于 2008-10-15T19:32:16.180 回答
-1
SELECT
  events.*
, COUNT(registrant_event.registrant_id) AS registrantsCount
FROM events
LEFT JOIN registrant_event ON events.id = registrant_event.event_id
GROUP BY events.id
于 2008-10-15T19:15:49.660 回答
-1
SELECT e.id, count(*) AS NumRegistrants
FROM events e
LEFT JOIN registrant_event re ON re.event_id=e.id
GROUP BY e.id

请注意,对于没有注册人的事件,这将返回 1 而不是 0。为了让它显示 0,你必须变得更复杂一点:

SELECT *,
    (SELECT COUNT(*) FROM registrant_event WHERE event_id=id) AS NumRegistrants
FROM events
于 2008-10-15T19:15:57.133 回答