2014-11-24 100 views
-1

我想從這個查詢中得到結果,但我在使用group_concat和max case時遇到了問題。如何在MAX中使用GROUP_CONCAT(CASE WHEN ...)?

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

+0

不知道我在下面。你能分享一些樣本數據和你試圖得到的結果嗎? – Mureinik 2014-11-24 07:38:53

+0

我不知道你在做什麼 – Strawberry 2014-11-24 07:39:08

+0

@Strawberry我在first_table列的home中選擇連接列時出現問題,而車輛已經連接了來自第二個表的連接值,現在我想從second_table獲取相關名稱。 – jones 2014-11-24 08:22:57

回答

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