gpt4 book ai didi

Mysql:从多个表中获取数据

转载 作者:行者123 更新时间:2023-11-29 06:50:27 25 4
gpt4 key购买 nike

我有 4 张 table 。

帖子:id、标题

标签:id、名称

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

最佳答案

您只需将条件括起来即可明确优先顺序。您还应该在 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

关于Mysql:从多个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com