gpt4 book ai didi

sql - 我怎样才能使这个查询更好?

转载 作者:行者123 更新时间:2023-12-03 17:49:12 26 4
gpt4 key购买 nike

我正在通过 GALAXQL 学习 SQL http://sol.gfxile.net/galaxql.html

我在第 17 课 - GROUP BY/HAVING

这是场景:

Let's look at couple of SELECT operations we haven't covered yet, namely GROUP BY and HAVING.

The syntax for these operations looks like this:


SELECT columns FROM table GROUP BY column HAVING expression

The GROUP BY command in a SELECT causes several output rows to be combined into a single row. This can be very useful if, for example, we wish to generate new statistical data as a table.

For example, to find out the highest intensities from stars for each class, we would do:


Select Class, Max(Intensity) As Brightness From Stars Group By Class Order By Brightness Desc

The HAVING operator works pretty much the same way as WHERE, except that it is applied after the grouping has been done. Thus, we could calculate the sum of brightnesses per class, and crop out the classes where the sum is higher than, say, 150.


SELECT class, SUM(intensity) AS brightness FROM stars GROUP BY class HAVING brightness < 150 ORDER BY brightness DESC

We could refer to columns that are not selected in the HAVING clause, but the results might be difficult to understand. You should be able to use the aggregate functions in the HAVING clause (for example, brightness < MAX(brightness)*0.5, but this seems to crash the current version of SQLite.

When combined with joins, GROUP BY becomes rather handy. To find out the number of planets per star, we can do:


SELECT stars.starid AS starid, COUNT(planets.planetid) AS planet_count FROM planets, stars WHERE stars.starid=planets.starid GROUP BY stars.starid

突出显示轨道最多的恒星(行星和卫星的组合)。
(注意验证查询有点繁重,所以请耐心等待
按“好的,我完成了..”)。


这是我的答案
SELECT stars.starid AS HighStar, 
(COUNT(planets.planetid) + COUNT(moons.moonid)) AS OrbitalsTotal
FROM stars
LEFT OUTER JOIN planets
ON stars.starid = planets.starid
LEFT OUTER JOIN moons
ON planets.planetid = moons.planetid
GROUP BY stars.starid
ORDER BY OrbitalsTotal DESC;

这个查询告诉我轨道数最多的恒星有 170 个轨道

那么:
INSERT INTO hilight SELECT result.HighStar
FROM result
INNER JOIN stars
ON result.HighStar = stars.starid
WHERE result.OrbitalsTotal = 170

我的问题是我怎样才能使这个查询更好?我不想对 170 个轨道进行硬编码,也不想创建第二个查询来插入数据。

最佳答案

SELECT stars.starid AS HighStar, 
(COUNT(planets.planetid) + COUNT(moons.moonid)) AS OrbitalsTotal
FROM stars
LEFT OUTER JOIN
planets ON stars.starid = planets.starid
LEFT OUTER JOIN
moons ON planets.planetid = moons.planetid
GROUP BY stars.starid
HAVING OrbitalsTotal = (SELECT MAX(Orbitals)
FROM (SELECT (COUNT(planets.planetid) + COUNT(moons.moonid)) Orbitals
FROM stars
LEFT OUTER JOIN
planets ON stars.starid = planets.starid
LEFT OUTER JOIN
moons ON planets.planetid = moons.planetid
GROUP BY stars.starid))

关于sql - 我怎样才能使这个查询更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454344/

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