我知道必须有一种方法可以做到这一点,但是对于我的一生,我无法弄清楚:
我有3个表要合并在一起(简化说明):
users
uid mail
1 [email protected]
2 [email protected]
3 [email protected]
profile_fields
fid name label
1 full_name Full Name
2 phone Phone
profile_values
uid fid value
1 1 Q Q
1 2 5555555555
2 1 Ww Ww
3 2 4444525411
我想获取表格的结果:
uid mail full_name phone
1 [email protected] Q Q 5555555555
2 [email protected] Ww Ww NULL
3 [email protected] NULL 44445454111
我已经尝试了各种具有不同JOIN条件的SELECT,但是我似乎无法弄清楚如何将profile_fields的行作为我的SELECT中的列
编辑:我也尝试过谷歌搜索,但我似乎无法弄清楚如何用词组谷歌。
最佳答案
采用:
SELECT u.uid,
u.mail,
MAX(CASE WHEN pf.name = 'full_name' THEN pv.value END) AS full_name,
MAX(CASE WHEN pf.name = 'phone' THEN pv.value END) AS phone
FROM USERS u
LEFT JOIN PROFILE_VALUES pv ON pv.uid = u.uid
JOIN PROFILE_FIELDS pf ON pf.fid = pv.fid
AND pf.name IN ('full_name', 'phone')
GROUP BY u.uid, u.mail
关于sql - MySQL将多对多连接成单行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2014144/