[英]How to make inner join with two conditions in MySQL
I have two tables in mysql database they are like following: 我在mysql数据库中有两个表,如下所示:
USERS : id, username
POSTS : id, post, poster_id, posted_id
Now I want to get the last 10 posts with the username of the poster_id(the man who wrote the post) and the username of the posted_id(the owner of the wall where the post has been written) 现在,我想获取最后10条帖子,其名称为poster_id(写帖子的人)的用户名和posted_id(写该帖子的墙的所有者)的用户名
I use this query : 我用这个查询:
SELECT posts.*,users.username as poster_username FROM posts
INNER JOIN users on posts.poster_id = users.id
ORDER BY timestamp DESC
LIMIT 0,10
but as you can see I just get one username for the poster_id is there a way to get the username of the posted_id within the same inner join statement?? 但是正如您所看到的,我只获得了一个poster_id的用户名,有没有一种方法可以在同一内部join语句中获取postd_id的用户名?
You should join user for twice: 您应该两次加入用户:
SELECT posts.*,
u1.username as poster_username,
u2.username as posted_username
FROM posts
INNER JOIN users u1 on posts.poster_id = u1.id
INNER JOIN users u2 on posts.posted_id = u2.id
ORDER BY timestamp DESC
LIMIT 0,10
The only requirement is to assign an alias to each table 唯一的要求是为每个表分配一个别名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.