当前位置:网站首页>How can MySQL query the records with the largest consumption amount of each user?

How can MySQL query the records with the largest consumption amount of each user?

2022-06-22 07:56:00 CSDN Q & A

There was a problem during the interview Query the consumption amount of each user Table structure [id, user_id, amount]

img

I want to :

SELECT    user_id,    max( amount ) FROM    orders GROUP BY    user_id

But I see that many statements given by people in the community use subqueries . Why is it so complicated ?
such as :

SELECT    o.* FROM    orders oRIGHT JOIN (    SELECT        max(amount) mxa,        user_id     FROM        orders     GROUP BY        user_id     ) m ON o.user_id = m.user_id AND o.amount = m.mxa



Take the answer :

Because the query fields are different . It's ok if you just check the maximum amount , But if you need to query other relevant information about the order , Your writing is not suitable .
Due to the use of group by grouping . The normal field of the query must be in the group field .

SELECT    o.* FROM    orders oRIGHT JOIN (    SELECT        max(amount) mxa,        user_id     FROM        orders     GROUP BY        user_id     ) m ON o.user_id = m.user_id AND o.amount = m.mxa

This method is aimed at real scenes , Query the order record information corresponding to each user's consumption amount .
The logic of implementation : The sub query finds the maximum order amount of each user , Then, it is related and matched according to the order amount , Find the corresponding order record .


原网站

版权声明
本文为[CSDN Q & A]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202151429132732.html