Вопрос

I just found this piece of SQL code that returns the row that contains the oldest person: Assume that you have a SQL table persons with two columns, name and age:

SELECT p1.name, p1.age
FROM persons p1
LEFT JOIN persons p2 ON p1.age < p2.age
WHERE p2.age IS NULL

Why does this return the maximum? Although I think I know what the left join does, I don't get this example since it uses the same table twice.

Can someone explain what happens here? I really want to learn this.

Это было полезно?

Решение

The left join restricts the returned values to only rows where the age in p2 is larger than the age in p1, the WHERE clause then says only return rows where p2.age IS NULL, there can only be one value in p1 that does not have a value in p2 that is higher; the highest value (given that the tables are the same data the highest value cannot have a higher value).

Changing the join to be p1.age > p2.age would return the lowest age.

EDIT - alternate solution

I think what may be a more efficient way to get the same result would be:

SELECT p1.Name, p1.Age
FROM persons p1
INNER JOIN (
    SELECT max(p2.age) As MaxAge FROM persons p2) As q ON (p1.age = q.MaxAge)

Or maybe

SELECT p1.Name, p1.Age
FROM persons p1
WHERE p1.age = (SELECT max(p2.age) As MaxAge FROM persons p2) 

Not a SQL master so there may be better ways, from a cursory glance at the execution plans they (the two alternatives above) look like they're doing the same but I'm working with a tiny amount of data.

Другие советы

Note: this is highly inefficient code. Basically it creates an ad hoc set of records SELECT p1.name, p1.age FROM persons p1 LEFT JOIN persons p2 ON p1.age < p2.age

For each and every p1, it will show all the p2 s that are older.

When you add the

WHERE p2.age IS NULL

It will show the p1, where there is no one that is older.

** Side one on efficiency**

The problem with the is that

FROM persons p1
LEFT JOIN persons p2 ON p1.age < p2.age

creates an ad hoc set of records that is 1/2 (number of persons)^2

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top