让我们选择3个包含所有行数的表:
TABLE Posts
PostPID
PostUID
PostText
TABLE Users
UserUID
UserName
TABLE Favorites
FavoriteUID
FavoritePID
现在,为了获取所有最近的帖子,我执行了一个查询,例如:
SELECT p.PostPID, p.PostUID, p.PostText, u.UserUID, u.UserName
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
ORDER BY p.PostPID DESC
LIMIT 0, 30
哪个工作正常。现在我想知道,我怎么才能得到某个UserUID喜欢的帖子?那么只有FavoriteUID = UserUID = X
的那个?
答案 0 :(得分:2)
您可以使用子查询。
...
Where p.PostUID in (select f.FavoritePID from Favorite f where f.FavoriteUID = UserUID)
...
答案 1 :(得分:2)
第二次加入将做同样的事情
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