Question

I built the following query using this MySQL doc page that I found through this StackOverflow question.

It gives me what I wanted: one record for each personkey, and the maximum (most recent) matchkey that that person has participated in.

but I don't understand the purpose of the "s1" and "s2," nor do I understand the construction used in the FROM line (and because I don't know what it's called, it's been difficult to search on it.) What is actually going on in this query?

SELECT personforeignkey, matchforeignkey

FROM   peoplematchesheroes s1

WHERE  matchforeignkey = (SELECT MAX(s2.matchforeignkey)
                          FROM peoplematchesheroes s2
                          WHERE s1.personforeignkey = s2.personforeignkey)

Note: I understand that this query is inefficient, but I want to understand the correlated-subquery construction before I try to optimize.

Was it helpful?

Solution

s1 and s2 are table aliases, in this case both for the same table 'peoplematchesheroes'. s1 is used as the alias for the outer query, and s2 for the inner correlated subquery.

It's not necessary to use a table alias for a correlated subquery, but in your case, since your inner query is also referring to the same table as the outer query, you need to alias them. Think of it as a resolution of scope, because otherwise it would be impossible to tell which 'personforeignkey' field you are referring to- the one from the table correlated subquery or from the outer one.

Hope this makes sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top