使用此SQL查询,我得到每个元值的结果,因此在这种情况下,每次都会得到2个结果。应该发生的是,每个meta_key都会获得它自己的列(user_phone
和full_name
)并且行中有meta_key
。
SELECT *
FROM invoice_users
INNER JOIN invoice_usermeta
on invoice_users.id = invoice_usermeta.user_id
WHERE meta_key='full_name' OR meta_key='user_phone';
我尝试了GROUP BY
,但那不对,我无法理解子查询...
invoice_users的数据库方案
ID | user_login | user_register
--------------------------------
0 username [Timestamp]
1 user2 [Timestamp]
2 user3 [Timestamp]
invoice_usermeta的数据库方案
ID | user_id | meta_key | meta_value
--------------------------------------
0 0 user_phone 0334234
1 0 full_name John Doe
2 1 user_phone 3453455
3 1 full_name Jane Doe
4 2 user_phone 78678678
5 3 full_name John Smith
我得到的结果:
ID | user_login | user_registered | meta_key | meta_value
0 username [Timestamp] full_name John Doe
0 username [Timestamp] user_phone 0334234
1 username [Timestamp] full_name Jane Doe
1 username [Timestamp] user_phone 3453455
等。
我想要什么
ID | user_login | user_registered | user_id |full_name | user_phone
0 username [Timestamp] 0 John Doe 0334234
1 username [Timestamp] 1 Jane Doe 3453455
等
答案 0 :(得分:2)
你提供的信息有点稀疏,但我会捅它。您可能想要做的事情是执行两次加入,如下所示:
SELECT u.*, m1.meta_value, m2.meta_value
FROM invoice_users u
LEFT OUTER JOIN invoice_usermeta m1
on u.id = m1.user_id
and m1.meta_key='user_phone'
LEFT OUTER JOIN invoice_usermeta m2
on u.id = m2.user_id
and m2.meta_key='full_name'
如果这还不够,因为你有很多元值,你会想要调查MySQL等价于Sql Server PIVOT的任何东西(很可能是PIVOT,我只是对MySQL不够了解)