轉自: http://www.maomao365.com/?p=10564 摘要: 下文講述MySQL資料庫查詢重覆數據時,只保留一條數據的方法 實現思路: 在MySQL資料庫中沒有row_number函數,所以我們需變向實現此功能。 定義臨時變數 @keyId,@infoB 每次查詢時 都重新對 ...
轉自: 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的信息