开发者

Multiple tables, multiple statement

开发者 https://www.devze.com 2023-02-17 17:23 出处:网络
Let\'s take 3 tables that has all tons of rows: TABLE Posts PostPID PostUID PostText TABLE Users UserUID UserName

Let's take 3 tables that has all tons of rows:

TABLE Posts

PostPID
PostUID
PostText

TABLE Users

UserUID
UserName

TABLE Favorites

FavoriteUID
FavoritePID

Now, in order to get all the recent posts I perform a query such as:

SELECT p.PostPID, p.PostUID, p.PostText, u.UserUID, u.UserName
    FROM开发者_StackOverflow社区 Posts AS p
        JOIN Users AS u
        ON p.PostUID = u.UserUID
    ORDER BY p.PostPID DESC
    LIMIT 0, 30

Which works fine. Now I was wondering, how could I get only the posts a certain UserUID prefers? So only the one with FavoriteUID = UserUID = X?


You could use a subquery.

...
Where p.PostUID in (select f.FavoritePID from Favorite f where f.FavoriteUID = UserUID)
...


second join will do the same

SELECT 
  p.PostPID, p.PostUID, p.PostText, u.UserUID, u.UserName
FROM 
  Posts AS p
JOIN 
  Users AS u ON p.PostUID = u.UserUID
Join 
  Favorites as f on f.FavoriteUID = u.UserUID and f.FavoritePID=p.PostPID
ORDER 
  BY p.PostPID DESC
LIMIT 0, 30
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号