如何在表mysql上联合行

时间:2014-06-22 10:36:41

标签: mysql sql

我在桌子上有这个值:

id|field_id|value_text
1|  1|  msk 
1|  2|  anton
1|  4|  adm@site.com
2|  1|  spb
2|  2|  serg
2|  4|  rr@sk.ru
3|  1|  rng
3|  2|  moya
3|  4|ore@kole.com

我怎么能这样:

id|city|name|email
1|msk|anton|adm@site.com
2|spb|serg|rr@sk.ru

请帮忙!

1 个答案:

答案 0 :(得分:0)

这看起来像是要pivot

尝试

SELECT 
    id, 
    MAX(CASE WHEN field_id = 1 THEN value_text END) AS city, 
    MAX(CASE WHEN field_id = 2 THEN value_text END) AS name, 
    MAX(CASE WHEN field_id = 4 THEN value_text END) AS email
FROM tbl
GROUP BY id

SQL Fiddle