简体   繁体   English

在MySQL中合并来自多个表的多行

[英]Combine multiple rows from multiple tables in MySQL

I have three tables; 我有三张桌子。

user table 用户

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

user_meta (metadata) table user_meta (元数据)表

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

country table 国家

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

I need to query by "rating" (eg " good ") and return the result set as; 我需要通过“评级”(例如“ ”)进行查询,并将结果集返回为;

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

Because the user_meta table has multiple rows that corresponds to a member in the user table, I was having trouble returning a combined set of values in one row. 因为user_meta表具有与user表中的成员相对应的多行,所以我很难在一行中返回一组组合的值。

Thank you. 谢谢。

Try 尝试

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

Output: 输出:

| 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 |

Here is SQLFiddle demo 这是SQLFiddle演示

You can just combine them in a JOIN . 您可以将它们合并为JOIN The LEFT JOIN s are there to allow for the row to show up even if the user has no phone/rating available; 即使用户没有可用的电话/费率,也可以使用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 . 要使用进行测试的SQLfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM