【发布时间】:2021-11-19 08:51:22
【问题描述】:
我是 SQL 新手。我正在使用 SQLite 编码并使用开源 Chinook 数据库。我有两个查询,从我的角度来看,它们应该返回相同的输出;但是,输出是不同的。为什么我的“SumOfUnitPrice”列的结果不同?
Chinook 数据库的 ER 图
查询 1:
select tracks.albumid, sum(tracks.unitprice) as SumOfUnitPrice from tracks
group by tracks.albumid having tracks.albumid in
(select albums.albumid from albums where albums.artistid in
(select artists.ArtistId from artists where artists.Name = "Audioslave"
)
)
结果 1:
+---------+----------------+
| AlbumId | SumOfUnitPrice |
+---------+----------------+
| 10 | 13.86 |
| 11 | 11.88 |
| 271 | 13.86 |
+---------+----------------+
查询 2:
select albums.albumid,
(select sum(tracks.unitprice) from tracks
group by tracks.albumid having tracks.albumid in
(select albums.albumid from albums where albums.artistid in
(select artists.ArtistId from artists where artists.Name = "Audioslave"
)
)
) as SumOfUnitPrice
from albums where albums.artistid in
(select artists.ArtistId from artists where artists.Name = "Audioslave"
)
结果 2:
+---------+----------------+
| AlbumId | SumOfUnitPrice |
+---------+----------------+
| 10 | 13.86 |
| 11 | 13.86 |
| 271 | 13.86 |
+---------+----------------+
【问题讨论】:
-
孩子们,这就是为什么要避免滥用子查询的原因。这可以通过几个内部连接变得超级解释,为什么需要这么多子查询?
标签: sql sqlite subquery correlated-subquery