如何从这个数据库设计中检索用户帖子?

时间:2011-12-28 21:08:18

标签: mysql sql database-design

使用mysql

数据库设计:

Users:
- userId
- userName

Posts:
- postId
- text

UserPosts (many-many):
- userId (FK)
- postId (FK)

我想检索所有用户发布的所有帖子。这就是我需要的:

- userName
- text

我不太确定如何编写此查询。我该怎么做3方式加入??

3 个答案:

答案 0 :(得分:0)

select Posts.text,
       Users.userName
FROM UserPosts
INNER JOIN Users on UserPosts.userId = Users.userId
INNER JOIN Posts on UserPosts.postId = Posts.postId

答案 1 :(得分:0)

SELECT userName, text FROM Users,Posts,UserPosts 
WHERE 
UserPosts.userID = Users.userId AND UserPosts.postID = Posts.postID 

答案 2 :(得分:-1)

SELECT 
      u.userName, 
      p.Text
FROM 
      UserPosts up 
INNER JOIN
      Users u 
ON  
      u.userID = up.userID
INNER JOIN 
      Posts p ON p.postID = up.postID