在Mysql中实现分组排序的方法首先,在命令行中启动mysql服务;service mysql start MySQL服务启动后,在命令行中输入mysql的用户名和密码登录到MySQL;mysql -u root -p登录到MySQL后,
首先,在命令行中启动mysql服务;
service mysql start
MySQL服务启动后,在命令行中输入mysql的用户名和密码登录到MySQL;
mysql -u root -p
登录到MySQL后,选择使用一个数据库;
use mysql;
最后,进入到数据库后,在数据库进行新建一个表;
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;
数据表创建好后,向表中插入数据;
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' );
最后,数据插入后,执行以下命令即可对表中的数据进行分组排序;
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
--结束END--
本文标题: mysql如何做分组排序
本文链接: https://lsjlt.com/news/116436.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0