我最近正在学习Self Join的SQL教程。
给出的表定义非常简单:
stops(id, name)
route(num, company, pos, stop)
此处,stop
属性是指在id
表格中提供名称的停靠点的stops
。
如果你看问题#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
在此,我已经知道id
的{{1}}为Craiglockhart
,53
的{{1}}为id
。到目前为止一切都很好。
但是,如果我在查询中添加Sighthill
或213
,结果会发生变化并找到更多结果:
ORDER BY name
具体来说,例如,伦敦路现在有8行而不是4行。
我一直在尝试了解这些结果的不同查询。除了排序之外,ORDER BY bstops.name
是否应该更改查询的实际结果?
答案 0 :(得分:1)
您可以在查询中使用LIMIT
关键字限制返回的记录数。我想他们正在添加像
... LIMIT 50 ...
指向您要提交的查询,以避免返回太多记录。
然后,显示的前50条记录可能因不同的ORDER BY
表达式而不同,因为记录是先排序的,然后排序的结果是有限的。
假设你有table
:
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
答案 1 :(得分:1)
除非苏格兰公共汽车停在同一站,不管旅行方向如何,我认为SQLZOO提供的答案是错误的。
我认为你可以通过这个查询模仿他们的答案......
SELECT a.num first_bus
, a.company first_company
, s1.name departing_from
, s2.name interchange
, d.num second_bus
, d.company second_company
, s3.name arriving_at
FROM route a
JOIN route b
ON b.num = a.num
AND b.pos <> a.pos
JOIN route c
ON c.stop = b.stop
JOIN route d
ON d.num = c.num
AND d.pos <> c.pos
JOIN stops s1
ON s1.id = a.stop
JOIN stops s2
ON s2.id = b.stop
JOIN stops s3
ON s3.id = d.stop
WHERE s1.name = 'Craiglockhart'
AND s3.name = 'Sighthill';
但是,我认为正确的答案是...的结果。
SELECT a.num first_bus
, a.company first_company
, s1.name departing_from
, s2.name interchange
, d.num second_bus
, d.company second_company
, s3.name arriving_at
FROM route a
JOIN route b
ON b.num = a.num
AND b.pos > a.pos
JOIN route c
ON c.stop = b.stop
JOIN route d
ON d.num = c.num
AND d.pos > c.pos
JOIN stops s1
ON s1.id = a.stop
JOIN stops s2
ON s2.id = b.stop
JOIN stops s3
ON s3.id = d.stop
WHERE s1.name = 'Craiglockhart'
AND s3.name = 'Sighthill';