现在已经坚持使用这个相当简单的MySQL查询了一天!简直不敢相信我忘记了基础知识。我有3个表 - user
,post
和favourite_post
。 post表的user_id是FK到用户表。
favourite_post
表有
user_id REFERENCES user(id)
post_id REFERENCES post(id)
timestamp
当用户收到帖子时,他的user_id,
post_id
和timestamp
会被插入到favourite_post表中。
我使用以下查询来检索最近的15篇帖子
SELECT post.id, post.text, post.timestamp, post.user_id, user.username
FROM post
INNER JOIN user
ON post.user_id = user.id
ORDER BY post.id
DESC LIMIT 15;
我需要做的就是通过加入favourite_post表来检查每个帖子是否已被当前用户(比如user_id = 1)所青睐。
答案 0 :(得分:2)
SELECT p.id, p.text, p.timestamp, p.user_id, u.username,
IF(ISNULL(fp.post_id), 'No', 'Yes') has_favourite
FROM post p
INNER JOIN user u
ON p.user_id = u.id
LEFT JOIN favourite_post fp
ON p.id = fp.post_id
AND u.id = fp.user_id
ORDER BY p.id DESC
LIMIT 15;
答案 1 :(得分:0)
试试这个:
SELECT p.id, p.text, fp.timestamp, p.user_id, u.username
FROM post p INNER JOIN user u
ON p.user_id = u.id
LEFT JOIN favourite_post fp
ON fp.user_id = p.user_id AND fp.post_id = p.id
WHERE p.user_id = your_user_id
ORDER BY p.id DESC
LIMIT 15;