gpt4 book ai didi

mysql - 使用 "ORDER BY"更改查询结果

转载 作者:可可西里 更新时间:2023-11-01 08:31:26 25 4
gpt4 key购买 nike

我最近正在学习 Self Join 的 SQL 教程.

给出的表定义非常简单:

stops(id, name)
route(num, company, pos, stop)

这里,stop 属性指的是在 stops 表中提供名称的站点的 id

如果您查看问题 #10,我提出了以下解决方案,该站点指示该解决方案产生了正确的结果:

SELECT distinct a.num, a.company, bstops.name, e.num, e.company FROM route a
JOIN route b ON (a.company = b.company AND a.num = b.num)
JOIN stops bstops ON bstops.id = b.stop
JOIN
(SELECT c.company, c.num, d.stop as d_stop FROM route c
JOIN route d ON (c.company = d.company AND c.num = d.num)
WHERE c.stop = 213) e
ON e.d_stop = b.stop
WHERE a.stop = 53

这里,我已经知道Craiglockhartid53,而id >Sighthill213。到目前为止一切都很好。

但是如果我在查询中添加 ORDER BY nameORDER BY bstops.name,结果会发生变化并找到更多结果:

SELECT distinct a.num, a.company, bstops.name, e.num, e.company FROM route a
JOIN route b ON (a.company = b.company AND a.num = b.num)
JOIN stops bstops ON bstops.id = b.stop
JOIN
(SELECT c.company, c.num, d.stop as d_stop FROM route c
JOIN route d ON (c.company = d.company AND c.num = d.num)
WHERE c.stop = 213) e
ON e.d_stop = b.stop
WHERE a.stop = 53 ORDER BY name

具体来说,例如,伦敦路现在有 8 行,而不是只有 4 行。

我一直在使用不同的查询来尝试理解这些结果。除了排序之外,ORDER BY 是否应该更改查询的实际结果?

最佳答案

您可以通过在查询中使用 LIMIT 关键字来限制返回的记录数。我想他们正在添加类似的内容

... LIMIT 50 ...

到您正在提交的查询,以避免返回过多的记录。

然后,显示的前 50 条记录对于不同的 ORDER BY 表达式可能不同,因为记录先排序,然后排序的结果是有限的。

假设您有这个:

Id Name
--+-------
0 |Andreas
1 |Lurker
2 |Gordon
3 |John

然后,

SELECT * FROM table ORDER BY Id LIMIT 2;

Id Name
--+-------
0 |Andreas
1 |Lurker

同时

SELECT * FROM table ORDER BY Name LIMIT 2;

Id Name
--+-------
0 |Andreas
2 |Gordon

关于mysql - 使用 "ORDER BY"更改查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849590/

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