我有三个表;
用户表
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 表有多行对应于 user 表中的一个成员,所以我无法在一行中返回一组组合值。
谢谢。
最佳答案
您可以将它们组合在一个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;
关于mysql - 合并 MySQL 中多个表的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18054582/