4

我正在尝试创建一个产生的查询:

VENUE | 2012-10-01 | 2012-10-02 | 2012-10-03
 01   |  OCCUPIED  |   EMPTY    |  OCCUPIED
 02   |   EMPTY    |   EMPTY    |  OCCUPIED
 03   |  OCCUPIED  |   EMPTY    |   EMPTY

从这两个表中:

场地表:

venue_id | venue
   1     |   01
   2     |   02
   3     |   03

事件表:

event_id |    start   |    end     | venue_id
   1     | 2012-10-01 | 2012-10-02 |    1
   2     | 2012-10-03 | 2012-10-04 |    1
   3     | 2012-10-03 | 2012-10-04 |    2
   4     | 2012-10-01 | 2012-10-02 |    3

任何人都可以提出解决这个问题的最佳方法吗?

我目前的做法是:

SELECT 
   venue,
   IF(start <= '2012-10-01' AND '2012-10-01' < end, 'OCCUPIED','EMPTY') AS '2012-10-01',
   IF(start <= '2012-10-02' AND '2012-10-02' < end, 'OCCUPIED','EMPTY') AS '2012-10-02',
   IF(start <= '2012-10-03' AND '2012-10-03' < end, 'OCCUPIED','EMPTY') AS '2012-10-03'
FROM Venue as v, Event as e
WHERE e.venue_id = v.venue_id
GROUP BY v.venue

但是,我没有得到想要的结果......我得到的是以下内容:

VENUE | 2012-10-01 | 2012-10-02 | 2012-10-03
 01   |  OCCUPIED  |   EMPTY    |   EMPTY
 02   |   EMPTY    |   EMPTY    |  OCCUPIED
 03   |  OCCUPIED  |   EMPTY    |   EMPTY

我究竟做错了什么?

4

1 回答 1

2

奇怪的是,您的 select 语句甚至不返回您发布的结果集中命名的列。另外,我注意到您在查询中重复了“2012-10-02”这一天。

SELECT 
   IF(start <= '2012-10-01' AND '2012-10-01' < end, 'OCCUPIED','EMPTY') AS '2012-10-01',
   IF(start <= '2012-10-02' AND '2012-10-02' < end, 'OCCUPIED','EMPTY') AS '2012-10-02',
   IF(start <= '2012-10-03' AND '2012-10-03' < end, 'OCCUPIED','EMPTY') AS '2012-10-03'
FROM Venue as v, Event as e
WHERE e.venue_id = v.venue_id
GROUP BY v.venue

编辑:

下面的两个事件共享相同的场所 ID 和场所字段,并且您的查询按场所分组,这样它在“2012-10-03”天抑制了 OCCUPIED 结果。

event_id |    start   |    end     | venue_id
   1     | 2012-10-01 | 2012-10-02 |    1
   2     | 2012-10-03 | 2012-10-04 |    1

SQL FIDDLE:http ://sqlfiddle.com/#!2/dc33f/20

您可以尝试添加一个像 MAX 这样的聚合函数来获取记录子集中包含的任何 OCCUPIED 事件:

SELECT e.*, v.venue,
   max(IF(start <= '2012-10-01' AND '2012-10-01' < end, 'OCCUPIED','EMPTY')) AS '2012-10-01',
   max(IF(start <= '2012-10-02' AND '2012-10-02' < end, 'OCCUPIED','EMPTY')) AS '2012-10-02',
   max(IF(start <= '2012-10-03' AND '2012-10-03' < end, 'OCCUPIED','EMPTY')) AS '2012-10-03'
  from event e,
       venue v
where e.venue_id = v.venue_id
GROUP BY v.venue

SQL FIDDLE:http ://sqlfiddle.com/#!2/dc33f/22

于 2012-10-07T15:30:35.283 回答