MySQL 查询以获取所有用户看到的帖子

MySQL query to fetch posts that all users seen

我需要获取从 MySQL 数据库中看到的 all 用户包含用户、帖子和 users_seen_posts tables 的帖子。

users_seen_posts table:

id |  user_id  | post_id  | 
---------------------------
 1 |  xxxxx4   | xxxxx1   |
 2 |  xxxxx3   | xxxxx6   |

这种类型的查询称为“关系划分”。在 SQL 中有几种方法可以解决它,但这种方法并不常见,所以 SQL 中的所有方法都有点笨拙。

这是一个解决方案,它将所有用户的数量与 users_seen_posts table 中发现的不同 user_id 的数量进行比较:

SELECT s.post_id
FROM users AS u
LEFT OUTER JOIN users_seen_posts AS s ON u.id = s.user_id
GROUP BY s.post_id
HAVING COUNT(*) = COUNT(DISTINCT s.user_id)

如果计数相等,则表示每个用户都代表了给定的 post,因此所有用户都看到了 post。