Skip to content
Advertisement

how to sort order of LEFT JOIN in SQL query?

OK I tried googling for an answer like crazy, but I couldn’t resolve this, so I hope someone will be able to help.

Let’s say I have a table of users, very simple table:

and I have another table of their cars and their prices.

Now what I need to do is something like this (feel free to rewrite):

Which returns:

But I need the most expensive car of a certain user, not the first entry found.

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

Advertisement

Answer

Try using MAX with a GROUP BY.


Further information on GROUP BY

The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, …) that will be applied to each group of records in turn. The database will return a single result record for each grouping.

For example, if we have a set of records representing temperatures over time and location in a table like this:

Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:

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