连接两个表并按类型创建虚拟列

时间:2016-03-17 15:03:57

标签: mysql join merge

我目前正在为学者考试开发某种日历。由于日历目前非常慢,我想加强它背后的MySQL。 我已经阅读了JOIN并尝试使用它们以便直接获得我需要的结果但我目前遇到了问题。

我有两张桌子(简化)

DAYS                           EVENTS
id | date                      id | day_id | class | text
1  | 2016-02-05                1  | 1      | a     | Example
2  | 2016-02-06                2  | 1      | b     | Example for Class b
etc.

现在,如果我选择一天,我想收到以下结果:

[0] => Array
    (
        [id] => 1
        [date] => 2016-01-25
        [a] => 1 (ID of the Event on that day with the class 'a')
        [b] => 2 (ID of the Event on that day with the class 'b')
        [c] => NULL
    )

但是我创建的查询到目前为止并没有合并结果:

[0] => Array
    (
        [id] => 1
        [date] => 2016-02-05
        [a] => 13
        [b] => 
        [c] => 
    )

[1] => Array
    (
        [id] => 11
        [date] => 2016-02-05
        [a] => 
        [b] => 14
        [c] => 
    )

我如何能够合并两个结果?我的查询如下:

SELECT d.*, 
     CASE WHEN e.class = 'a' THEN e.id ELSE NULL END AS a,
     CASE WHEN e.class = 'b' THEN e.id ELSE NULL END AS b,
     CASE WHEN e.class = 'c' THEN e.id ELSE NULL END AS c
  FROM examplan_days d
      LEFT JOIN examplan_events e ON d.id = e.day_id

1 个答案:

答案 0 :(得分:1)

我认为你想聚合:

SELECT d.*, 
       MAX(CASE WHEN e.class = 'a' THEN e.id END) AS a,
       MAX(CASE WHEN e.class = 'b' THEN e.id END) AS b,
       MAX(CASE WHEN e.class = 'c' THEN e.id END) AS c
FROM examplan_days d LEFT JOIN
     examplan_events e
     ON d.id = e.day_id
GROUP BY d.id;

如果您在某一天可以有多个课程,那么您应该使用GROUP_CONCAT()而不是MAX()