收拾残局,过滤部分字段重复的数据

select distinct可以去掉重复记录。
disctinct将重复的记录忽略,但它忽略的是完全一致的重复记录,而不是其中某个字段重复的记录,或者说,distinct查询一个字段时好使,多个字段就不好使。

所以用聚合函数和group by实现
注意:group by只能跟聚合函数搭配使用

例表


ID username password TRDESC ……………………
1 A abcdef QR
2 A abcdef W34
3 A bbbbbb AD
4 B aaaaaa asdf

查询username和password组合起来的条件不能重复的查询结果(这个都能重复,不能不说这是个烂摊子)

当username和password重复时,取ID最大的记录:
select * from mytable where ID in(select max(ID) from mytable group by username,password)

当username和password重复时,取ID最小的记录:
select * from mytable where ID in(select min(ID) from mytable a group by username,password)

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word