在同一个表

时间:2018-03-23 13:57:23

标签: mysql sql

我有以下查询:

SELECT a.id FROM table_a a
LEFT JOIN 
(
    SELECT aid, GROUP_CONCAT(name) AS workers FROM table_b WHERE lv = 1 GROUP BY aid
) b ON b.aid = a.id
LEFT JOIN 
(
    SELECT aid, GROUP_CONCAT(name) AS writers FROM table_b WHERE lv = 2 GROUP BY aid
) c ON c.aid = a.id

我决定使用LEFT JOIN

在单个CASE .. WHEN .. THEN .. ELSE .. END中缩短内容

执行以下操作:

SELECT a.id FROM table_a a
LEFT JOIN 
(
    SELECT aid,
    CASE 
      WHEN lv = 1 THEN GROUP_CONCAT(name) AS workers
      WHEN lv = 2 THEN GROUP_CONCAT(name) AS writers
    END
    FROM table_b GROUP BY aid
) bc ON bc.aid = a.id

但它似乎不适用于Alias内部。在这种情况下,如何缩短LEFT JOIN?或者我只是坚持两个 LEFT JOIN s?

错误/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS workers WHEN lv = 2 THEN GROUP_CONCAT(name) AS writers END FROM table_b GROUP BY' at line 1 */

P.S。查询为LIMIT 1

1 个答案:

答案 0 :(得分:1)

尝试以下查询:

SELECT 
   GROUP_CONCAT(case when lv = 1 then name end) as workers, 
   GROUP_CONCAT(case when lv = 2 then name end) as writers
 FROM table_b as b
 JOIN table_a as a ON a.id=b.aid
GROUP BY a.id

SQL Fidder演示:http://sqlfiddle.com/#!9/490931/1