在mysql中实现分组排序的方法
1.首先,在命令行中启动MySQL服务;
service mysql start
2.MySQL服务启动后,在命令行中输入mysql的用户名和密码登录到MySQL;
mysql -u root -p
3.登录到MySQL后,选择使用一个数据库;
use mysql;
4.最后,进入到数据库后,在数据库进行新建一个表;
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;
5.数据表创建好后,向表中插入数据;
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' );
6.最后,数据插入后,履行以下命令便可对表中的数据进行分组排序;
SELECT orders_id,user_id,add_time,rank FROM (
SELECT @rownum:=@rownum+1 AS rownum,
IF(@x=uo.user_id,@rank:=@rank+1,@rank:=1) rank,
@x:=uo.user_id,
orders_id,user_id,add_time
FROM
user_orders uo,
( SELECT @rownum:=0,@rank:=0) init
ORDER BY user_id ASC , add_time DESC
)result
WHERE rank=2
本文来源:https://www.yuntue.com/post/58442.html | 云服务器网,转载请注明出处!