how to sort order of LEFT JOIN in SQL query?

后端 未结 5 1669
悲哀的现实
悲哀的现实 2020-12-08 04:25

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 t

5条回答
  •  执念已碎
    2020-12-08 05:07

    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
    

提交回复
热议问题