1

有两个表,“用户”和“列表”,以及一个将用户与列表相关联的多对多“订阅”表(因此具有外键user_idlist_id),一个 SQL 查询来查找所有不这样做的用户将是什么?没有任何特定的订阅list_id(自然包括根本没有订阅的用户)?

4

2 回答 2

3

再次爆发的时间not exists

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
  )
于 2009-12-02T15:55:29.537 回答
0

我用过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)) }
于 2021-08-26T16:03:08.770 回答