Home > Database > Mysql Tutorial > body text

SQL语句技巧之去除重复行

WBOY
Release: 2016-06-07 15:10:55
Original
2775 people have browsed it

去除表中重复行数据,可能大家立马就想到的是用 DISINTCT 关键字,但 DISINTCT 只能是去除表中所有列都相同的行,若碰到需要去除表中多个字段重复的行(即:部份相同,部份不相同),那么该如何做呢?我通过多年数据库编写经验,整理了如下方法,供大家参考

去除表中重复行数据,可能大家立马就想到的是用DISINTCT关键字,但DISINTCT只能是去除表中所有列都相同的行,若碰到需要去除表中多个字段重复的行(即:部份相同,部份不相同),那么该如何做呢?我通过多年数据库编写经验,整理了如下方法,供大家参考和使用。

方法1:适用于返回较少字段

select F1,F2,F3,MAX(F4) FROM TABLENAME GROUP BY F1,F2,F3

方法2:适用于返回行所有字段,需指定不相同的字段

select * FROM TABLENAME T where F4=(select MAX(F4) from TABLENAME where T.F1=F1 and T.F2=F2 and T.F3=F3)

方法3:适用于返回行所有字段,需指定不相同的字段【找出需要去除的行】

SELECT T1.* FROM TABLENAME AS T1,(SELECT F1,F2,MAX(F3) AS F3 FROM TABLENAME GROUP BY F1,F2 HAVING COUNT(*)>1) AS T2

WHERE T1.F3 AND T1.F1=T2.F1 AND T1.F2=T2.F2

http://www.zuowenjun.cn/post/2014/08/02/10.html

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!