SQL根据B表内容修改A表内容,查询表中重复记录,删除掉重复项只保留一条

以下sql是a,b两张表通过关联条件id修改a表值,如果b表有重复数据记录,选第一条更新,红色条件为附加限制条件,具体视情况而定;

UPDATE a SET
name = b.fname,
pwd = b.lname
FROM b
WHERE a.id = b.id
AND a.id in (2,3)

以下sql为查询单表中重复记录;

select * from b t1 where t1.fname in  (select t2.fname from b t2 group by t2.fname having count(*) > 1)

以下为转载SQL语句,删除掉重复项只保留一条,提示(如果表没有主键,导致ID重复,可利用rownum来做判断保留min(rownum)),下边也有函数处理方法

在几千条记录里,存在着些相同的记录,如何能用SQL语句,删除掉重复的呢
1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断 
select * from people 
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) 

2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录 
delete from people 
where   peopleName in (select peopleName    from people group by peopleName      having count(peopleName) > 1) 
and   peopleId not in (select min(peopleId) from people group by peopleName     having count(peopleName)>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)

6.消除一个字段的左边的第一位:

update tableName set [Title]=Right([Title],(len([Title])-1)) where Title like '村%'

7.消除一个字段的右边的第一位:

update tableName set [Title]=left([Title],(len([Title])-1)) where Title like '%村'

8.假删除表中多余的重复记录(多个字段),不包含rowid最小的记录 
update vitae set ispass=-1
where peopleId in (select peopleId from vitae group by peopleId

postgresql 删除ID重复数据

原来表设计没有主键导致SQL重复执行时会产生多条一模一样的主键,现在需要对原来的表建立主键,需要对ID重复的数据进行删除,只保留一条虽然数据完全一致,但好在pgsql数据库提供了ctid的隐藏列,根据此列可以把只保留最小ctid的相同数据行。于是写了以下存储过程来处理。方便多了。再也不错这种问题了。

CREATE OR REPLACE FUNCTION delete_repeat(tablename varchar)
RETURNS bigint AS
$BODY$
DECLARE
rec RECORD;
sql varchar;
BEGIN
RAISE INFO '处理表名:%', tablename;
IF NOT exists(select * from pg_class where relname = tablename) then
RAISE INFO '处理表不存在:%', tablename;
RETURN -1;
END IF;

FOR rec in EXECUTE('select id from '||tablename||' group by id having count(id) > 1') LOOP
RAISE INFO 'id:%', rec.id;
sql := 'delete from ' || tablename || ' where id = ''' || rec.id|| ''' and
ctid <> (select min(ctid) from ' || tablename || ' where id = ''' || rec.id|| ''')';
execute sql;
RAISE INFO 'sql:%', sql;
END LOOP;
RETURN 1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

运行select delete_repeat('tablename');

上一篇:解决获取IP地址时出现“在一个非套…


下一篇:数据库中is null(is not null)与=null(!=null)的区别