一对多关系上的 SQL 连接,其中没有一个与给定值匹配

发布于 2024-09-10 20:25:43 字数 643 浏览 2 评论 0原文

假设我有两个表

User
-----
id
first_name
last_name

User_Prefs
-----
user_id
pref

User_Prefs 中的示例数据可能是

user_id | pref
  2     |  SMS_NOTIFICATION
  2     |  EMAIL_OPT_OUT
  2     |  PINK_BACKGROUND_ON_FRIDAYS

并且某些用户可能在 User_Prefs 中没有相应的行。

我需要查询任何没有 EMAIL_OPT_OUT 作为其(可能有很多,可能没有)User_Pref 行之一的用户的名字和姓氏。

SELECT DISTINCT u.* from User u
LEFT JOIN User_Prefs up ON (u.id=up.user_id)
WHERE up.pref<>'EMAIL_OPT_OUT'

让我得到至少有一行不是“EMAIL_OPT_OUT”的每个人,这当然不是我想要的。我希望每个人都没有与“EMAIL_OPT_OUT”匹配的行。

有没有办法让联接类型和联接条件过滤掉我想在此处省略的行?或者我需要子查询吗?

Say I have two tables

User
-----
id
first_name
last_name

User_Prefs
-----
user_id
pref

Sample data in User_Prefs might be

user_id | pref
  2     |  SMS_NOTIFICATION
  2     |  EMAIL_OPT_OUT
  2     |  PINK_BACKGROUND_ON_FRIDAYS

And some users might have no corresponding rows in User_Prefs.

I need to query for the first name and last name of any user who does NOT have EMAIL_OPT_OUT as one of their (possibly many, possibly none) User_Pref rows.

SELECT DISTINCT u.* from User u
LEFT JOIN User_Prefs up ON (u.id=up.user_id)
WHERE up.pref<>'EMAIL_OPT_OUT'

gets me everyone who has at least one row that isn't "EMAIL_OPT_OUT", which of course is not what I want. I want everyone with no rows that match "EMAIL_OPT_OUT".

Is there a way to have the join type and the join conditions filter out the rows I want to leave out here? Or do I need a sub-query?

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

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

发布评论

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

评论(2

星光不落少年眉 2024-09-17 20:25:43

我个人认为“哪里不存在”类型的子句可能更容易阅读,但这里有一个带有执行相同操作的联接的查询。

select distinct u.* from User u
left join User_Prefs up ON u.id = up.user_id and up.pref = 'EMAIL_OPT_OUT'
where up.user_id is null

I personally think a "where not exists" type of clause might be easier to read, but here's a query with a join that does the same thing.

select distinct u.* from User u
left join User_Prefs up ON u.id = up.user_id and up.pref = 'EMAIL_OPT_OUT'
where up.user_id is null
铜锣湾横着走 2024-09-17 20:25:43

为什么不将用户首选项作为布尔字段存储在用户表中?这将显着简化您的查询。

SELECT * FROM User WHERE EMAIL_OPT_OUT = false

Why not have your user preferences stored in the user table as boolean fields? This would simplify your queries significantly.

SELECT * FROM User WHERE EMAIL_OPT_OUT = false
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文