一对多关系上的 SQL 连接,其中没有一个与给定值匹配
假设我有两个表
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我个人认为“哪里不存在”类型的子句可能更容易阅读,但这里有一个带有执行相同操作的联接的查询。
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.
为什么不将用户首选项作为布尔字段存储在用户表中?这将显着简化您的查询。
Why not have your user preferences stored in the user table as boolean fields? This would simplify your queries significantly.