MySQL Query在第二个表中查找值

时间:2016-11-22 15:49:26

标签: mysql

我是MySQL新手,由于某种原因,这个解决方案让我望而却步。我有两张桌子:

users
|--------------------------------------------------|
| user_id | user_name | email                      |
|--------------------------------------------------|
| 1       | user1     | user1@somedomain.com       |
| 2       | user2     | user2@someotherdomain.com  |
| 3       | user3     | user3@yetanotherdomain.com |
|--------------------------------------------------|

user_meta
|---------------------------------|
| user_id | meta_key | meta_value |
|---------------------------------|
| 1       | first_name | john     |
| 1       | last_name  | doe      |
| 2       | first_name | joe      |
| 2       | last_name  | schmoe   |
| 3       | first_name | harry    |
| 3       | last_name  | pickle   |
|---------------------------------|

我想要一个产生此输出的查询:

|---------------------------------------------------------------|
| user_id | first_name | last_name | email                      |
|----------------------------------|----------------------------|
| 1       | john       | doe       | user1@somedomain.com       |
| 2       | joe        | schmoe    | user2@someotherdomain.com  |
| 3       | harry      | pickle    | user3@yetanotherdomain.com |
|----------------------------------|----------------------------|

我尝试了几种类型的连接并尝试了子查询,但必须有一些我想念的简单方法。我可以在输出中获得名字或姓氏,但不能同时获得两者。任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:0)

我在这里使用了左外连接,因为无法保证给定user_id存在first_name或last_name键。在这些情况下,我们仍然会显示user_id和电子邮件,但名称会有NULL。

SELECT U1.user_id, M1.first_name, M2.last_name, U1.email
FROM users U1
LEFT OUTER JOIN user_meta M1 ON M1.user_id = U1.user_id AND M1.meta_key = 'first_name'
LEFT OUTER JOIN user_meta M2 ON M2.user_id = U1.user_id AND M2.meta_key = 'last_name'

答案 1 :(得分:0)

试试这会有所帮助

select 
    u.user_id, 
    meta_value as first_name, 
    meta_value as last_name, 
    email
from users u left outer join user_meta um on u.user_id = um.user_id
group by u.user_id