我有两个 mysql 表,我想在一个查询中合并在一起。最好用一个例子来描述:
table: users
| user_id | username |
| 1 | jason |
| 2 | justin |
table: user_data
| user_id | key | data |
| 1 | email | jason@email.com |
| 1 | phone | 555-123-4567 |
| 2 | email | justin@email.com|
| 2 | phone | 555-765-4321 |
query results:
| user_id | username | email | phone |
| 1 | jason | jason@email.com | 555-123-4567 |
| 2 | justin | justin@email.com | 555-765-4321 |
您可以假设所有用户的密钥都非常统一(即所有用户都有电子邮件和电话)。我的第一个想法是做这样的事情,但我很好奇是否有更好的方法:
SELECT *,e.data as email,p.data as phone FROM users u
LEFT JOIN user_data AS e ON e.user_id=u.user_id AND `key`='email'
LEFT JOIN user_data AS p ON p.user_id=u.user_id AND `key`='phone';