使用左连接查询选择用户详细信息

时间:2015-05-27 17:16:45

标签: mysql

我有以下2个表:

user_profile

+----+------------+-------------+
| id | first_name |  last_name  |
+----+------------+-------------+
| 17 | Hugh       | Jackman     |
| 18 | Keanu      | Reeves      |
| 19 | Tom        | Cruise      |
+----+------------+-------------+

like_posts

+---------+---------+
| post_id | user_id |
+---------+---------+
| 31      | 18      |
| 31      | 19      |
+---------+---------+

我需要数据:user_id,first_name,last_name from" user_profile"所有那些喜欢post_id的用户在" like_posts"表。例如,如果post_id是31,那么我想要post_id = 31的用户的first_name和last_name。以下是所需的结果:

+------------+-------------+
| first_name |  last_name  |
+------------+-------------+
| Keanu      | Reeves      |
| Tom        | Cruise      |
+------------+-------------+

这是我一直在尝试的查询,但我没有得到理想的结果。我正在获取表中所有用户的详细信息。我是mysql的初学者。

SELECT user_profile.first_name, user_profile.last_name FROM `user_profile` 
LEFT JOIN
(
SELECT like_posts.user_id from `like_posts` WHERE like_posts.post_id = 31
)
liked_users 
ON user_profile.id = liked_users.user_id

2 个答案:

答案 0 :(得分:0)

使用内部联接选择两个表中的匹配记录

SELECT user_profile.first_name, user_profile.last_name FROM `user_profile` 
JOIN `like_posts`

ON user_profile.user_id = like_posts.user_id      

 WHERE like_posts.post_id = 30

答案 1 :(得分:0)

http://sqlfiddle.com/#!9/b60ae/1

SELECT l.*, u.first_name, u.last_name
FROM like_posts l
LEFT JOIN user_profile u
ON u.id = l.user_id
WHERE l.post_id = 31

或者,如果您只想要2列:

SELECT u.first_name, u.last_name
FROM like_posts l
LEFT JOIN user_profile u
ON u.id = l.user_id
WHERE l.post_id = 31