I was practicing self join at SQLZOO and here's a thing I do not understand towards the following question(Q10):
The question is: Find the routes involving two buses that can go from Craiglockhart to Sighthill. Show the bus no. and company for the first bus, the name of the stop for the transfer, and the bus no. and company for the second bus The Answer is :
SELECT DISTINCT a.num, a.company, stopb.name , c.num, c.company
FROM route as a JOIN route as b
ON (a.company = b.company AND a.num = b.num)
JOIN ( route c JOIN route d ON (c.company = d.company AND c.num= d.num))
JOIN stops as stopa ON (a.stop = stopa.id)
JOIN stops as stopb ON (b.stop = stopb.id)
JOIN stops as stopc ON (c.stop = stopc.id)
JOIN stops as stopd ON (d.stop = stopd.id)
WHERE stopa.name = 'Craiglockhart' AND stopd.name = 'Sighthill'
AND stopb.name = stopc.name
ORDER BY LENGTH(a. num), b.num, stopb.id, LENGTH(c.num), d.num
I am quite confused about the result of
FROM route a JOIN route b ON (a.company = b.company AND a.num = b.num)
JOIN ( route c JOIN route d ON (c.company = d.company AND c.num= d.num))
The second JOIN doesn't contain ON, so what's the join criteria here? what would be the result of this join?
The result is a cross product. Every row from the left matched to every row on the right.
For this type of join, without an ON clause, we typically include the CROSS
keyword before JOIN
, to alert the future reader that the omission of the ON
clause was intentional, and not an oversight.
SELECT ...
FROM a
CROSS
JOIN b
ORDER BY ...
We get the same result if we specify ON expr
with an expression that evaluates to true for every row.
SELECT ...
FROM a
JOIN b
ON 1=1
ORDER BY ...
Result is the same as if we had omitted the ON
clause entirely... a row from a
matches each and every row from b
.
In this case, I tend to omit the ON
clause (where the expression/condition always evaluates to TRUE) and specify CROSS JOIN
instead. I think that makes the intent more clear.
MySQL is more liberal than some other databases, which require the CROSS
keyword when the ON
clause is omitted.
In MySQL, the keywords INNER
and CROSS
are optional, and have no influence. That is, JOIN
and INNER JOIN
and CROSS JOIN
are all synonymous. So our usage style is informed by compatibility with other databases, and being mindful of a future reader that may be trying to decipher our statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.