我有4张桌子。
发布:id,title
标记:id,name
post_tag :id,post_id,tag_id
user_read_activity :id,user_id,post_id
User_read_activity包含用户已阅读的帖子。 Post_tag包含链接到标签的帖子。一个帖子可以有多个标签。我需要根据用户关注的某些标记获取用户未读帖子,并删除用户可能不喜欢的某些帖子。
我已经提出了这个代码。但这是错误的。这也给了我用户阅读帖子。但基于标签这些都是正确的。只需要纠正未读部分。请帮帮我。
如果代码错误,也请帮我修改代码。
SELECT DISTINCT post.* FROM post
INNER JOIN post_tag ON post.id = post_tag.post_id
INNER JOIN tag
WHERE tag.id = 21 OR tag.id = 26 OR tag.id = 63 OR tag.id = 86 OR tag.id = 11
AND post.id != 1088 AND post.id != 338 AND post.id != 1396
AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)
ORDER BY post.likes DESC LIMIT 5
答案 0 :(得分:2)
您只需要围绕您的条件使用括号来明确优先顺序。您还应该在post_tag和tag之间进行适当的连接:
SELECT DISTINCT post.* FROM post
INNER JOIN post_tag ON post.id = post_tag.post_id
INNER JOIN tag ON post_tag.tag_id = tag.id
WHERE (tag.id = 21 OR tag.id = 26 OR tag.id = 63 OR tag.id = 86 OR tag.id = 11)
AND post.id != 1088 AND post.id != 338 AND post.id != 1396
AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)
ORDER BY post.likes DESC LIMIT 5
或者@dimwittedanimal建议的IN
标准可以使用。
SELECT DISTINCT post.* FROM post
INNER JOIN post_tag ON post.id = post_tag.post_id
INNER JOIN tag ON post_tag.tag_id = tag.id
WHERE tag.id IN (21, 26, 63, 86, 11)
AND post.id NOT IN (1088, 338, 1396)
AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)
ORDER BY post.likes DESC LIMIT 5