MySQL GROUP_CONCAT并将两行合二为一

时间:2014-03-21 08:49:12

标签: mysql group-concat

我有桌子

id | industry_id | type | key
1        1           0    word1
2        1           1    word2
3        1           0    word3
4        1           1    word4
5        2           0    word5
6        2           1    hello
7        2           0    world

结果我需要得到表

industry_id | title       | description
1           | word1 word3 | word2 word4
2           | word5 world | hello

这意味着所有类型为0的单词都会转到title,类型1指向描述

现在我几乎可以得到我想要的查询(但每个行业仍然可以获得2条记录)

SELECT industry_id, type, GROUP_CONCAT(`key` SEPARATOR ' ') AS TEXT FROM table GROUP BY industry_id, type

3 个答案:

答案 0 :(得分:0)

试试这样:

SELECT industry_id, type, 
  GROUP_CONCAT(if(type = 0,key,'') SEPARATOR ' ') AS title,
GROUP_CONCAT(if(type = 1,key,'') SEPARATOR ' ') AS description
   FROM table GROUP BY industry_id, type

答案 1 :(得分:0)

SELECT industry_id
     , MAX(CASE WHEN type = 0 THEN text END) title
     , MAX(CASE WHEN type = 1 THEN text END) description
  FROM
     ( SELECT industry_id
            , type
            , GROUP_CONCAT(`key` SEPARATOR ' ') TEXT 
         FROM my_table 
        GROUP 
           BY industry_id
            , type
     ) x
 GROUP
    BY industry_id;

考虑重命名key列!

答案 2 :(得分:0)

您按industry_id, type分组,因此每个行业ID都会获得4行和2行尝试此操作

SELECT industry_id, 
GROUP_CONCAT(CASE WHEN `type`=0 THEN `key` END SEPARATOR ' ') AS title,
GROUP_CONCAT(CASE WHEN `type`=1 THEN `key` END SEPARATOR ' ') AS description
FROM Table1 
GROUP BY industry_id

See Fiddle