Skip to content
Advertisement

SQL: create global alias for nested SELECT to be used in another nested SELECT

Let’s assume I’ve got a database with two tables: people which contains person’s id and his/her birth year for each person and parents which contains the (parent_id, child_id) pairs to represent the relative relationships between people. To make the explanation easier let’s assume each person has either 0 children or 1 child. Here is an example of the data in the database (as a set of SQL statements to create it on MySQL):

Result:

The people table

The parents table

Now I want to make up a query which will retrieve the id of the person, whose child was born at the earliest age of the parent (for example, if I was born in 1234 and my child was born in 1300, then my age when my child was born was 1300 - 1234 = 66 and I would like to find a person which got their child earlier than others).

I have made up some queries for it, but each of them either didn’t work or had duplications or both. The one I like most is

But this one fails in MySQL with the error:

How do I fix the error? Another thing I am worried about is that as a result, I will select not only the parent’s id but also the id of one of his/her children. Is it possible to avoid it? Probably there is a better way to select the data I’m looking for?

Advertisement

Answer

You can get the ages by using joins:

To get all the rows with the minimum, use window functions:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement