MySQL implements grouping and sorting

Posted by Iron Bridge on Mon, 16 Dec 2019 15:39:05 +0100

We want to extract the second order information of all users in descending order according to the user group and the order time of the user.
This belongs to group sorting. There are built-in functions in Oracle that can be implemented, but in mysql, it's a bit troublesome:

CREATE TABLE user_orders (orders_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
add_time INT UNSIGNED NOT NULL,
PRIMARY KEY(orders_id),
KEY(user_id),
KEY(add_time)
)ENGINE=INNODB DEFAULT CHARSET utf8 COMMENT 'mysql Implementation of group sorting test table';
 
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('1','1','1');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('2','1','2');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('3','1','3');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('4','2','1');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('5','2','2');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('6','2','3');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('7','3','1');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('8','3','2');
INSERT INTO `user_orders` (`orders_id`, `user_id`, `add_time`) VALUES('9','3','3');
 
SELECT orders_id,user_id,add_time,rank FROM (
SELECT  @rownum:=@rownum+1 AS rownum,# Line number
    IF(@x=uo.user_id,@rank:=@rank+1,@rank:=1) rank,#Process ranking. If @ x equals user'id, @ x is initialized and @ rank is increased by 1
    @x:=uo.user_id, # Initialize @ x, @ x is the intermediate variable, which is initialized after rank. Therefore, when rank is initialized, @ x is null or the value of the previous user ﹐ ID
    orders_id,user_id,add_time 
FROM  
    user_orders  uo,
    (SELECT @rownum:=0,@rank:=0) init # Initialization information table
ORDER BY user_id ASC, add_time DESC
)result
WHERE rank=2

Important: the key is how to assign @ X. Once you understand the @ x assignment, you can immediately understand the origin of rank.
Since it's sorting by groups, it's certainly numbering by groups. Each group must have an unchanging column, otherwise what group by? Grasp this feature and naturally understand the meaning of rank. Another point should be noted is that there are two sorting conditions when group by is used, otherwise the group is unstable

Topics: MySQL Oracle