合并MySQL中多个表的多行

时间:2013-08-05 09:20:05

标签: mysql sql

我有三张桌子;

用户

   id     first_name     last_name     country 
   2      John           Doe           USA
   3      Jimmy          Biglips       FRA

user_meta (元数据)表

user_id   meta_key       meta_value
   2      phone          3333
   2      rating         Good
   3      phone          7777
   3      rating         Bad

国家/地区

country_id     country     country_fullname
    1          USA         United States of America
    2          FRA         France

我需要按“评分”进行查询(例如“良好”)并将结果集返回为;

id  first_name    last_name     phone     rating    country     country_fullname 
2   John          Doe           33333     Good      USA         United States of America

由于 user_meta 表有多行与用户表中的成员对应,因此我无法在一行中返回一组合并的值。

谢谢。

2 个答案:

答案 0 :(得分:2)

尝试

SELECT u.id,
       u.first_name,
       u.last_name,
       MIN(CASE WHEN meta_key = 'phone' THEN meta_value END) phone,
       MIN(CASE WHEN meta_key = 'rating' THEN meta_value END) rating,
       u.country,
       c.country_fullname
  FROM user u LEFT JOIN user_meta m 
    ON u.id = m.user_id LEFT JOIN country c
    ON u.country = c.country
 GROUP BY u.id

输出:

| ID | FIRST_NAME | LAST_NAME | PHONE | RATING | COUNTRY |         COUNTRY_FULLNAME |
-------------------------------------------------------------------------------------
|  2 |       John |       Doe |  3333 |   Good |     USA | United States of America |
|  3 |      Jimmy |   Biglips |  7777 |    Bad |     FRA |                   France |

这是 SQLFiddle 演示

答案 1 :(得分:2)

您只需将它们合并到JOIN即可。即使用户没有可用的电话/评级,LEFT JOIN也可以显示该行;

SELECT u.id, u.first_name, u.last_name, p.meta_value phone, r.meta_value rating,
       u.country, c.country_fullname
FROM user u
LEFT JOIN user_meta p ON u.id=p.user_id AND p.meta_key='phone'
LEFT JOIN user_meta r ON u.id=r.user_id AND r.meta_key='rating'
JOIN country c ON u.country=c.country;

An SQLfiddle to test with