简体   繁体   中英

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

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

You can just combine them in a JOIN . The LEFT JOIN s are there to allow for the row to show up even if the user has no phone/rating available;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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