I have 4 tables.
post : id, title
tag : id, name
post_tag : id, post_id, tag_id
user_read_activity : id, user_id, post_id
User_read_activity contains posts that user has read. Post_tag contains post that are linked to tags. one post can have more than one tag. I need to fetch user unread posts based on certain tags that the user follows and also remove certain posts which the user may not like.
I have come up with this code. But this is wrong. This also gives me user read posts. But based on tags these are correct. Just need to correct the unread part. Please help me with this.
Please also help me with the code correction if the code is wrong by any means.
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
You just need brackets around your conditions to be explicit about order of precedence. You should also have a proper join between post_tag and 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
Alternatively the IN
criteria advised by @dimwittedanimal would work.
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
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.