SQL 聚合未产生结果

发布于 2024-11-07 04:57:32 字数 408 浏览 0 评论 0原文

为什么这会给出空结果?我正在尝试获取非主管员工的最小值、最大值和平均值。

SELECT MIN(salary), MAX(salary), AVG(salary)
FROM employee
WHERE ssn NOT IN
(SELECT superssn FROM employee)

员工表的一部分

SSN       SUPERSSN
--------- ---------
888665555
333445555 888665555
987654321 888665555
987987987 987654321
123456789 333445555
999887777 987654321
666884444 333445555
453453453 333445555

Why is this giving an empty result? I'm trying to get the min, max, and average of the set of employees who aren't supervisors.

SELECT MIN(salary), MAX(salary), AVG(salary)
FROM employee
WHERE ssn NOT IN
(SELECT superssn FROM employee)

Part of employee table

SSN       SUPERSSN
--------- ---------
888665555
333445555 888665555
987654321 888665555
987987987 987654321
123456789 333445555
999887777 987654321
666884444 333445555
453453453 333445555

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

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

发布评论

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

评论(2

二智少女猫性小仙女 2024-11-14 04:57:32

您需要从内部查询中排除空值。否则,外部查询将检查列表,其中列表值之一为 NULL,并且该比较不会返回任何内容。所以,正确的查询应该是这样的。

SELECT MIN(salary), MAX(salary), AVG(salary)
FROM employee
WHERE ssn NOT IN
(SELECT superssn FROM employee where superssn IS NOT NULL)

You need to exclude nulls from the inner query. Otherwise the outer query checks against a list where one of the list values is NULL and that comparison doesn't return anything. So, the correct query should be something like.

SELECT MIN(salary), MAX(salary), AVG(salary)
FROM employee
WHERE ssn NOT IN
(SELECT superssn FROM employee where superssn IS NOT NULL)
初见 2024-11-14 04:57:32

这就是为什么 NOT EXISTS 在语义上是正确的并且更可靠的原因

SELECT MIN(salary), MAX(salary), AVG(salary)
FROM employee E
WHERE NOT EXISTS (SELECT * FROM employee E2 WHERE E.ssn = E2.superssn)

NOT IN 列表中的任何 NULL 总是会由于布尔逻辑而给出错误。您的 superssn 值为 NULL。

This is why NOT EXISTS is semantically correct and more reliable

SELECT MIN(salary), MAX(salary), AVG(salary)
FROM employee E
WHERE NOT EXISTS (SELECT * FROM employee E2 WHERE E.ssn = E2.superssn)

Any NULL in the NOT IN list will always give false thanks to boolean logic. You have a NULL superssn value.

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