MySQL 数据库查询数据,过滤重复数据保留一条数据---(MySQL中的row_number变相实现方法)

时间:2022-03-05 23:12:40

转自: http://www.maomao365.com/?p=10564 摘要:

下文讲述MySQL数据库查询重复数据时,只保留一条数据的方法 
实现思路:
在MySQL数据库中没有row_number函数,所以我们需变向实现此功能。
 

--1.基础数据表查看
mysql> select * from `maomao365.com`;
+-------+------------+
| keyId | infoB |
+-------+------------+
| 1 | mysql test |
| 129 | sql |
| 12913 | sql |
| 12913 | sql |
| 12913 | sql |
+-------+------------+
5 rows in set (0.00 sec) ---2 群组编号
mysql> select if(@keyId=a.keyId and @infoB=a.infoB,@r:=@r+1,@r:=1) as rowNumber,a.*,@keyId:=a.keyId,@infoB:=a.infoB
-> from (select @keyId:=null,@infoB:=null,@r:=0) r, (select keyId,infoB from `maomao365.com` order by keyId) a;
+-----------+-------+------------+-----------------+-----------------+
| rowNumber | keyId | infoB | @keyId:=a.keyId | @infoB:=a.infoB |
+-----------+-------+------------+-----------------+-----------------+
| 1 | 1 | mysql test | 1 | mysql test |
| 1 | 129 | sql | 129 | sql |
| 1 | 12913 | sql | 12913 | sql |
| 2 | 12913 | sql | 12913 | sql |
| 3 | 12913 | sql | 12913 | sql |
+-----------+-------+------------+-----------------+-----------------+
5 rows in set (0.00 sec) ---3 重复数据只显示一条
mysql> select * from (select if(@keyId=a.keyId and @infoB=a.infoB,@r:=@r+1,@r:=1) as rowNumber,a.*,@keyId:=a.keyId,@infoB:=a.infoB
-> from (select @keyId:=null,@infoB:=null,@r:=0) r, (select keyId,infoB from `maomao365.com` order by keyId) a
-> ) as t where t.rowNumber =1;
+-----------+-------+------------+-----------------+-----------------+
| rowNumber | keyId | infoB | @keyId:=a.keyId | @infoB:=a.infoB |
+-----------+-------+------------+-----------------+-----------------+
| 1 | 1 | mysql test | 1 | mysql test |
| 1 | 129 | sql | 129 | sql |
| 1 | 12913 | sql | 12913 | sql |
+-----------+-------+------------+-----------------+-----------------+
3 rows in set (0.00 sec)

定义临时变量 @keyId,@infoB
每次查询时 都重新对 @keyId,@infoB 赋值
在赋值前,都采用If对其进行判断,如果当前行记录信息和临时变量中的值相同时,则作为相同数据@r变量加1,否则@r变量变为1
采用以上模式,可以将重复的行记录进行编号

最后对重新编号后的记录,检索出row_number等于1的信息
  MySQL 数据库查询数据,过滤重复数据保留一条数据---(MySQL中的row_number变相实现方法)