mysql重复记录取最后一条记录方法
如下表:
代码如下 | 复制代码 |
CREATE TABLE `t1` ( |
数据如下:
代码如下 | 复制代码 |
MySQL> SELECT * FROM t1; +--------+---------------------+ |
其中userid不唯一,要求取表中每个userid对应的时间离现在最近的一条记录.初看到一个这条件一般都会想到借用临时表及添加主建借助于join操作之类的.
给一个简方法:
代码如下 | 复制代码 |
MySQL> SELECT userid,substring_index(group_concat(atime ORDER BY atime DESC),",",1) AS atime FROM t1 GROUP BY userid; +--------+---------------------+ |
查询及删除重复记录
删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录
代码如下 | 复制代码 |
delete from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1) |
3、查找表中多余的重复记录(多个字段)
代码如下 | 复制代码 |
select * from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) |
4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录
代码如下 | 复制代码 |
delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) |
5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录
代码如下 | 复制代码 |
select * from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) |
补充:数据库,mysql教程