我正在尝试创建一个生成:
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
我究竟做错了什么?
最佳答案 奇怪的是,你的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
编辑:
以下两个活动共享相同的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