gpt4 book ai didi

Mysql 其他表中未引用的行数

转载 作者:行者123 更新时间:2023-11-28 23:32:31 25 4
gpt4 key购买 nike

使用 mysql,我跟踪用户是否在其他表中看到了帖子

Table Posts:
id body
1 test1

Table user_views
post_id user_id
1 1

上面的行表示用户 1 已经看到帖子 1

我的问题是如何计算用户未看到的帖子数 - 在 user_views 中有多少行的帖子数?

过程:每次用户打开我运行的博客页面

select count(uv.post_id) as views_count,posts.id,posts.body 
from posts left join user_views uv on uv.post_id = posts.id
group by posts.id

这将返回所有帖子以及已经看到该帖子的用户数量

但我想在侧边栏上显示用户尚未看到的帖子数,以便用户可以知道有他尚未看到的新帖子。

我的第一次尝试是

select count(*) from posts 
where posts.id not in select post_id from user_views
where post_id = posts.id and user_id = 1

但它不是有效的 mysql,我怀疑它是最好的方法!

最佳答案

A LEFT JOIN (或者就此而言,正确的连接)与 IS NULL 检查是要走的路。

SELECT COUNT(*) FROM Post as posts
LEFT JOIN user_views
ON posts.id = user_views.post_id
WHERE user_id = 1 AND user_views.post_id IS NULL

我注意到您已经有一个用于不同目的的 LEFT JOIN。我相信可以将其更改为 INNER JOIN 以获得性能提升。

另请注意,在 mysql 中使用子查询时,需要用括号将其括起来以避免语法错误。更正后的查询将获得与我给出的结果相同的结果。哪个更好将取决于您的指标。

select count(*) from Post as posts
where posts.id not in (select post_id from user_views
where post_id = posts.id and user_id = 1)

关于Mysql 其他表中未引用的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36947790/

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