这是一个涉及连接的SQL问题,比我想要的更多。
我有2个表,一个事件表和歌手表
EVENTS event_id event_name num_attendees tickets_sold tickets_promo event_date ... many other fields
SINGERS event_id singer
我正在尝试从事件表中获取事件统计信息,如果执行了任何歌手列表。
EVENTS: event_id num_attendees tickets_sold 1 15 2500 2 5 1575 Singers at the event: event_id singer 1 bob 1 jane 2 bob
我对bob或jane演唱的事件的统计感兴趣:
SELECT count(e.event_id) as count_events, sum(num_attendees) as sum_attentees,
sum(tickets_sold) as sum_tickets_sold
FROM `events` e
INNER JOIN singers s ON s.event_id = e.event_id
AND s.singer IN ("bob", "jane")
WHERE event_date ...
给我一个错误的计数和总和,因为加入会给我2个事件1的记录,1个事件2的记录和事件的数量将是3。
我该如何编写这个SQL?感谢。
答案 0 :(得分:3)
SELECT count(e.event_id) as count_events,
sum(num_attendees) as sum_attentees,
sum(tickets_sold) as sum_tickets_sold
FROM events e
WHERE e.event_id IN
(SELECT DISTINCT event_id FROM singers WHERE singer IN ("bob", "jane"));
答案 1 :(得分:2)
SELECT count(e.event_id) as count_events,
sum(num_attendees) as sum_attentees,
sum(tickets_sold) as sum_tickets_sold
FROM `events` e
WHERE event_date ...
AND EXISTS (
SELECT 1
FROM singers s
WHERE s.event_id = e.event_id
AND s.singer IN ("bob", "jane")
);
答案 2 :(得分:2)
我不认为JOIN真的适合这里。尝试使用子查询来获取您感兴趣的事件列表:
SELECT count(e.event_id) as count_events, sum(num_attendees) as sum_attentees,
sum(tickets_sold) as sum_tickets_sold
FROM events WHERE event_id IN
(SELECT DISTINCT event_id FROM singers WHERE singer_id IN ('Bob', 'Jane'))
AND event_date ...
答案 3 :(得分:0)
我认为您也可以使用加入 如
SELECT count(e.event_id) as count_events,
sum(e.num_attendees) as sum_attentees,
sum(e.tickets_sold) as sum_tickets_sold
FROM events e join (SELECT DISTINCT event_id FROM singers WHERE singer_id IN ('Bob', 'Jane')) s
on e.event_id = s.event_id