根据两个表上的值获取不同的数据集

时间:2018-10-13 18:22:23

标签: mysql

SELECT users.firstname,
users.lastname,
users.username,
users.image_url,
posts.status,
posts.created_at as created_at,
posts.updated_at as updated_at,
share.post_user_id as user_id,
posts.id,
share.message as message,
share.user_id as share_user_id
FROM `share` INNER JOIN `posts` ON share.post_id = posts.id 
INNER JOIN `users` ON users.id = share.user_id

因此,正如您在此处看到的那样,我正在基于users.id = share.user_id从表users中获取名字,姓氏和用户名。共享表如下:

分享

  • 消息

  • user_id

  • post_user_id

  • post_id

现在如何获取基于users.id = share.post_user_id的名称集?

1 个答案:

答案 0 :(得分:0)

您只需要使用别名(例如user2)在表用户上进行另一个内部联接

    SELECT users.firstname,
    users.lastname,
    users.username,
    users.image_url,
    posts.status,
    posts.created_at as created_at,
    posts.updated_at as updated_at,
    share.post_user_id as user_id,
    posts.id,
    share.message as message,
    share.user_id as share_user_id,
    users2.firstname,
    users2.lastname,
    users2.username,
    FROM `share` 
    INNER JOIN `posts` ON share.post_id = posts.id 
    INNER JOIN `users` ON users.id = share.user_id
    INNER JOIN `users`  AS user2 ON users2.id = post_user_id.user_id