[mysql] 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:

id | userName
3    Michael
4    Mike
5    George

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

id | belongsToUser | carPrice
1    4               5000
2    4               6000
3    4               8000

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

   SELECT
      `userName`,
      `carPrice`
   FROM `users`
   LEFT JOIN `cars`
   ON cars.belongsToUser=users.id
   WHERE `id`='4'

Which returns:

Mike | 5000

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 ?

This question is related to mysql sql greatest-n-per-group

The answer is


Older MySQL versions this is enough:

SELECT
    `userName`,
    `carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice`) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'

Nowdays, if you use MariaDB the subquery should be limited.

SELECT
    `userName`,
    `carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice` LIMIT 18446744073709551615) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'

try this out:

   SELECT
      `userName`,
      `carPrice`
   FROM `users`
   LEFT JOIN `cars`
   ON cars.belongsToUser=users.id
   WHERE `id`='4'
   ORDER BY `carPrice` DESC
   LIMIT 1

Felix


Several other answer give the solution using MAX. In some scenarios using an agregate function is either not possilbe, or not performant.

The alternative that I use a lot is to use a correlated sub-query in the join...

SELECT
   `userName`,
   `carPrice`
FROM `users`
LEFT JOIN `cars`
ON cars.id = (
  SELECT id FROM `cars` WHERE BelongsToUser = users.id ORDER BY carPrice DESC LIMIT 1
)
WHERE `id`='4'

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

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

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to greatest-n-per-group

How to select the rows with maximum values in each group with dplyr? MAX function in where clause mysql Pandas get topmost n records within each group SQL Left Join first match only Select info from table where row has max date FORCE INDEX in MySQL - where do I put it? GROUP BY having MAX date How can I select rows with most recent timestamp for each key value? Select row with most recent date per user How to select id with max date group by category in PostgreSQL?