From: http://www.maomao365.com/?p=10564 Abstract:
The following describes how to keep only one piece of data when MySQL database queries duplicate data
Implementation ideas:
There is no row Ou number function in MySQL database, so we need to change direction to implement this function.
--1.View basic data table 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 Group number 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 Duplicate data display only one 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)
Define temporary variable @ keyId,@infoB
Every time you query, @ keyId,@infoB will be re assigned
Before the assignment, if is used to judge it. If the current line record information and the value in the temporary variable are the same, then add 1 as the same data @ r variable, otherwise @ r variable becomes 1
In the above mode, duplicate line records can be numbered
Finally, for the renumbered records, the information that row u number is equal to 1 is retrieved