如何将GROUP_CONCAT与MAX一起使用(CASE WHEN ...)?

时间:2014-11-24 07:29:43

标签: mysql case group-concat

我想从这个查询中获取结果但是我在使用group_concat和max case时遇到了问题。

SELECT
  t1.id,
  t1.name,
  MAX(CASE WHEN t2.code = t1.f_name THEN t2.name END) AS name2,
  MAX(CASE WHEN t2.code = t1.l_name THEN t2.name END) AS name3,
  MAX(CASE WHEN t2.code = t1.a_name THEN t2.name END) AS name4,
  GROUP_CONCAT(MAX(CASE WHEN FIND_IN_SET(t3.code,t1.vehicles) THEN t3.name END) AS car_owned)
  GROUP_CONCAT(MAX(CASE WHEN FIND_IN_SET(t3.code,t1.homes) THEN t3.name END) AS home_owned)
FROM
  first_table AS t1 LEFT JOIN second_table AS t2
  ON t2.code IN (t1.f_name, t1.l_name, t1.a_name)
  LEFT JOIN second_table AS t3 ON FIND_IN_SET(t3.code,t1.vehicles) > 0 OR FIND_IN_SET(t3.code,t1.homes) > 0
GROUP BY
  t1.id,
  t1.name

任何帮助谢谢。小提琴是here

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT
  t1.id,
  t1.name,
  CASE WHEN t2.code = t1.f_name THEN t2.name END AS name2,
  CASE WHEN t2.code = t1.l_name THEN t2.name END AS name3,
  CASE WHEN t2.code = t1.a_name THEN t2.name END AS name4,
  CASE WHEN FIND_IN_SET(t3.code,t1.vehicles) > 0 THEN GROUP_CONCAT(DISTINCT(t3.name END)) AS car_owned)
  CASE WHEN FIND_IN_SET(t3.code,t1.homes) > 0 THEN GROUP_CONCAT(DISTINCT(t3.name)) END AS home_owned)
FROM
  first_table AS t1 LEFT JOIN second_table AS t2
  ON t2.code IN (t1.f_name, t1.l_name, t1.a_name)
  LEFT JOIN second_table AS t3 ON FIND_IN_SET(t3.code,t1.vehicles) > 0 OR FIND_IN_SET(t3.code,t1.homes) > 0
GROUP BY
  t1.id,
  t1.name

小提琴是here