SQL 查询查找没有订阅指定列表的用户(多对多)

发布于 2024-08-13 06:46:48 字数 173 浏览 7 评论 0原文

有两个表,“users”和“lists”,以及一个将用户与列表相关的多对多“订阅”表(因此具有外键 user_idlist_id) ,要查找所有没有任何订阅且具有特定 list_id 的用户(自然包括根本没有订阅的用户),单个 SQL 查询会怎样?

Having two tables, "users" and "lists", and a many-to-many "subscriptions" table relating users to lists (thus having foreign keys user_id and list_id), what would be a single SQL query to find all the users that don't have any subscription with a specific list_id (naturally including the users that have no subscriptions at all)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜血缘 2024-08-20 06:46:49

是时候再次突破不存在了:

select
  u.user_id
from
  users u
where
  not exists (
    select 1 from subscriptions s where s.user_id = u.user_id and s.list_id = N
  )

Time to break out not exists again:

select
  u.user_id
from
  users u
where
  not exists (
    select 1 from subscriptions s where s.user_id = u.user_id and s.list_id = N
  )
演出会有结束 2024-08-20 06:46:49

我使用了 NOT IN 并且效果很好:

SELECT Count(*)
FROM   "users"
WHERE  "users"."id" NOT IN (SELECT "users"."id"
                            FROM   "users"
                                   INNER JOIN "unsubscribes"
                                           ON "unsubscribes"."user_id" =
                                              "users"."id"
                            WHERE  "unsubscribes"."list" = $1) 

Ruby on Rails 作用域作为奖励:

  scope :unsubscribed, -> (list) { joins(:unsubscribes).where(unsubscribes: { list: list }) }
  scope :subscribed, -> (list) { where.not(id: User.unsubscribed(list)) }

I used NOT IN and it works well:

SELECT Count(*)
FROM   "users"
WHERE  "users"."id" NOT IN (SELECT "users"."id"
                            FROM   "users"
                                   INNER JOIN "unsubscribes"
                                           ON "unsubscribes"."user_id" =
                                              "users"."id"
                            WHERE  "unsubscribes"."list" = $1) 

Ruby on Rails scopes as a bonus:

  scope :unsubscribed, -> (list) { joins(:unsubscribes).where(unsubscribes: { list: list }) }
  scope :subscribed, -> (list) { where.not(id: User.unsubscribed(list)) }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文