简体   繁体   中英

how to do a retrieve user posts from this database design?

Using mysql

DB design:

Users:
- userId
- userName

Posts:
- postId
- text

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

I want to retrieve all the posts made by all the users. This is what I need:

- userName
- text

I'm not quite sure how to write this query. How do I do this 3 way join ??

select Posts.text,
       Users.userName
FROM UserPosts
INNER JOIN Users on UserPosts.userId = Users.userId
INNER JOIN Posts on UserPosts.postId = Posts.postId
SELECT userName, text FROM Users,Posts,UserPosts 
WHERE 
UserPosts.userID = Users.userId AND UserPosts.postID = Posts.postID 
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM