5

我有两张桌子。我需要所有organizer_id在 2010 年到 2012 年间组织所有活动的人。

event
--------- 
event_id
name
year


event_organizer
---------
event_id
organizer_id

我试过这样的事情:

SELECT organizer_id 
  FROM event_organizer
 WHERE event_id IN (SELECT event_id 
                      FROM event 
                     WHERE year>=2010 AND year<=2012);

但它不起作用,因为我只需要organizer_id在 2010 年和 2012 年之间组织了所有事件的那些。我不知道查询应该如何看起来像我想要的那样工作。

4

2 回答 2

9

你可以写:

SELECT t1.organizer_id
  FROM ( SELECT eo.organizer_id,
                COUNT(1) AS num_events
           FROM event_organizer eo
           JOIN event e
             ON eo.event_id = e.event_id
          WHERE e.year BETWEEN 2010 AND 2012
          GROUP
             BY eo.organizer_id
       ) t1
  JOIN ( SELECT COUNT(1) AS num_events
           FROM event e
          WHERE e.year BETWEEN 2010 AND 2012
       ) t2
    ON t1.num_events = t2.num_events
;

(上面的想法是:对于每个组织者,找出他在 2010 年和 2012 年之间组织了多少活动。然后,将其与 2010 年和 2012 年之间的活动总数进行比较。如果这两个数字相同,然后组织者组织了那个时期的所有活动。)

或者,您可以编写:

SELECT organizer_id
  FROM organizer       -- I assume you have an 'organizer' table?
 WHERE organizer_id NOT IN
        ( SELECT o.organizer_id
            FROM event e
           CROSS
            JOIN organizer o
            LEFT
           OUTER
            JOIN event_organizer eo
              ON e.event_id = eo.event_id
             AND o.organizer_id = eo.organizer_id
           WHERE e.year BETWEEN 2010 and 2012
             AND eo.event_id IS NULL
        )
;

(这个想法是:找到所有活动组织者配对,使得组织者没有组织活动。然后,返回所有未出现在任何此类配对中的组织者。)

于 2013-01-12T20:04:09.120 回答
4

我认为进行此类查询的最简单方法是使用聚合:

with events as (
    select event_id
    FROM event 
    WHERE year>=2010 AND year<=2012
)
select organizer_id
from event_organizer eo
where event_id in (select event_id from events)
group by organizer_id
having count(distinct event_id) = (select count(*) from events)
于 2013-01-12T20:58:45.393 回答