在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