轉自: http://www.maomao365.com/?p=10564 摘要:mysql
下文講述MySQL數據庫查詢重複數據時,只保留一條數據的方法
實現思路:
在MySQL數據庫中沒有row_number函數,因此咱們需變向實現此功能。
sql
--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的信息
函數