gpt4 book ai didi

mysql - 我不确定 : Is this an anti-join?

转载 作者:行者123 更新时间:2023-11-29 11:37:30 25 4
gpt4 key购买 nike

我正在研究著名的 SQLzoos 的第一个问题,并且正在研究 using Null 部分:http://sqlzoo.net/wiki/Using_Null

问题是:

List the teachers who have NULL for their department.

相应的 SQL 查询是:

SELECT t.name
FROM teacher t
WHERE t.dept IS NULL

这是一种反连接吗?具体来说,这是左反连接吗?

最佳答案

这根本不是联接。

该语句仅过滤没有指定部门的教师的记录。

设置差异

教师和院系的设置差异,教师\院系将是一种“反加入”

SELECT
t.name
FROM teacher t
LEFT JOIN department d ON d.id = t.dept_id
WHERE d.id IS NULL

乍一看,这个语句的作用与您的语句的作用相同,如果强制执行外键引用,它将保证完全做到这一点。然而,此语句的一个用途是检索分配到已被删除的系的教师(例如,如果英语文学系和英语作为第二语言系被重组为英语系)

对称差异

另一个“反连接”是对称差异,它从两个集合中选择元素,如果它们无法连接,即

(teacher \ department) U (department \ teacher)

我想不出使用教师和部门的激励示例,但在支持 FULL OUTER JOIN 的数据库上编写对称差异的一种方法是:

SELECT
t.name
FROM teacher t
FULL OUTER JOIN department d ON d.id = t.dept_id
WHERE d.id IS NULL OR t.id IS NULL

对于 MySQL,该语句必须写为两个语句的并集。

SELECT
t.name teacher_name, d.name department_name
FROM teacher t
LEFT JOIN department d ON d.id = t.dept_id
WHERE d.id IS NULL

UNION ALL

SELECT
t.name teacher_name, d.name department_name
FROM teacher t
LEFT JOIN department d ON d.id = t.dept_id
WHERE t.id IS NULL

浏览我的一个项目,我发现了对称差异的一种用途:

上下文:

I have three tables: users, users_gameplay_summary, users_transactions_summary. I needed to email those users who created their accounts in the past 7 days AND one of the following have transacted but have not played or played but have not transacted.

为了获取列表,我有这个查询(注意,这是为 Postgresql 编写的,不适用于 MySQL,但它说明了对称差异用例):

SELECT 
COALESCE(g.user_id, t.user_id) user_id
FROM users_gameplay_summary g
FULL OUTER JOIN users_transactions_summary t ON t.user_id = g.user_id

WHERE COALESCE(g.user_id, t.user_id) IN (
SELECT user_id
FROM users
WHERE created_at > CURRENT_DATE - '7 day'::interval)
AND (g.user_id IS NULL OR t.user_id IS NULL)

关于mysql - 我不确定 : Is this an anti-join?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36341153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com