gpt4 book ai didi

SQLZOO : Derived Table inside the subquery vs Derived Table outside a subquery?

转载 作者:行者123 更新时间:2023-12-01 03:33:53 29 4
gpt4 key购买 nike

https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial 的问题 7

“找到每个大陆中最大的国家(按面积),显示大陆、名称和面积:”

我不明白为什么

SELECT continent, name, area FROM world
WHERE area >= ALL
(SELECT area FROM world as x
WHERE x.continent IN (continent))

结果:

+-----------+--------+----------+
| continent | name | area |
+-----------+--------+----------+
| Eurasia | Russia | 17125242 |
+-----------+--------+----------+

但是

SELECT continent, name, area FROM world as x
WHERE area >= ALL
(SELECT area FROM world
WHERE x.continent IN (continent))

SELECT continent, name, area FROM world as x
WHERE area >= ALL
(SELECT area FROM world as y
WHERE x.continent IN (y.continent))

两者都给出了正确的结果:

+---------------+------------+----------+
| continent | name | area |
+---------------+------------+----------+
| Africa | Algeria | 2381741 |
| Oceania | Australia | 7692024 |
| South America | Brazil | 8515767 |
| North America | Canada | 9984670 |
| Asia | China | 9596961 |
| Caribbean | Cuba | 109884 |
| Europe | Kazakhstan | 2724900 |
| Eurasia | Russia | 17125242 |
+---------------+------------+----------+

我不明白为什么在子查询内有派生表与在子查询外有派生表不同。它们不应该都一样吗?

最佳答案

您的查询:

SELECT continent, name, area FROM world
WHERE area >= ALL
(SELECT area FROM world as x
WHERE x.continent IN (continent))

等同于:

SELECT continent, name, area FROM world
WHERE area >= ALL
(SELECT area FROM world as x
WHERE x.continent IN (x.continent))
<=>
SELECT continent, name, area FROM world
WHERE area >= ALL(SELECT area FROM world as x)
--(assuming that continent is defined as NOT NULL)
-- In result you are searching for biggest country(correct answer - Russia)

为避免这种情况,您应该明确为列名添加前缀:

SELECT continent, name, area FROM world
WHERE area >= ALL
(SELECT area FROM world as x
WHERE x.continent IN (continent))
=>
SELECT continent, name, area FROM world
WHERE area >= ALL
(SELECT x.area FROM world as x
WHERE x.continent IN (world.continent))

关于SQLZOO : Derived Table inside the subquery vs Derived Table outside a subquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53198186/

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