sqlite 如何只保留表中的一行,删除重复的行?

wd2eg0qa  于 2022-12-13  发布在  SQLite
关注(0)|答案(9)|浏览(462)

我有一个数据表,在[名称a数据行中有许多重复项目。我只想为每个项目保留一个数据列。
下面列出了重复项,但我不知道如何删除重复项并只保留一个:

SELECT name FROM members GROUP BY name HAVING COUNT(*) > 1;
  • 谢谢-谢谢
wb1gzix0

wb1gzix01#

请看下面的问题:从表中删除重复行。
改编后的公认答案来自那里(这是我的答案,所以这里没有“盗窃”......):
假设您有一个唯一的ID字段,您可以用一种简单的方法来执行此操作:您可以删除除ID之外相同但名称不具有“最小ID”的所有记录。
示例查询:

DELETE FROM members
WHERE ID NOT IN
(
    SELECT MIN(ID)
    FROM members
    GROUP BY name
)

如果您没有唯一索引,我的建议是添加一个自动增量唯一索引。主要是因为它的设计很好,但也因为它允许您运行上面的查询。

jtjikinw

jtjikinw2#

将唯一的表选择到新表中,删除旧表,然后重命名临时表以替换它,可能会更容易。

#create a table with same schema as members
CREATE TABLE tmp (...);

#insert the unique records
INSERT INTO tmp SELECT * FROM members GROUP BY name;

#swap it in
RENAME TABLE members TO members_old, tmp TO members;

#drop the old one
DROP TABLE members_old;
wbgh16ku

wbgh16ku3#

我们有一个庞大的数据库,删除重复记录是常规维护过程的一部分。我们使用DISTINCT选择唯一的记录,然后将它们写入TEMPORARY TABLE。在TRUNCATE之后,我们将TEMPORARY数据写回TABLE。
这是一种方法,并作为一个存储的程序工作。

wsxa1bj1

wsxa1bj14#

如果我们想先查看您要删除的行,请删除它们。

with MYCTE as (
    SELECT DuplicateKey1
        ,DuplicateKey2 --optional
        ,count(*) X
    FROM MyTable
    group by DuplicateKey1, DuplicateKey2
    having count(*) > 1
) 
SELECT E.*
FROM MyTable E
JOIN MYCTE cte
ON E.DuplicateKey1=cte.DuplicateKey1
    AND E.DuplicateKey2=cte.DuplicateKey2
ORDER BY E.DuplicateKey1, E.DuplicateKey2, CreatedAt

完整示例位于http://developer.azurewebsites.net/2014/09/better-sql-group-by-find-duplicate-data/

os8fio9y

os8fio9y5#

您可以通过匹配字段将表与自己连接,并删除不匹配行

DELETE t1 FROM table_name t1 
LEFT JOIN tablename t2 ON t1.match_field = t2.match_field
WHERE t1.id <> t2.id;
nwwlzxa7

nwwlzxa76#

delete dup row keep one表中有重复的行,可能有些行没有重复的行,如果表中有重复的或单个的行,则保留一行。表中有两个列ID和名称,如果我们必须从表中删除重复的名称并保留一个。它在我的端工作正常。您必须使用此查询。

DELETE FROM tablename
WHERE id NOT IN(

 SELECT id FROM
(
    SELECT MIN(id)AS id
    FROM tablename
    GROUP BY name HAVING 
    COUNT(*) > 1
)AS a )
AND id NOT IN(
(SELECT ids FROM
(
SELECT MIN(id)AS ids
    FROM tablename
    GROUP BY name HAVING 
    COUNT(*) =1
)AS a1
)
)

删除前的表如下,请参见屏幕截图:enter image description here在删除表后如下所示请参见此查询的屏幕截图删除amit和akhil重复的行并保留一条记录(amit和akhil):
enter image description here

daolsyd0

daolsyd07#

如果要从表中删除重复记录。

CREATE TABLE tmp SELECT lastname, firstname, sex
FROM user_tbl;
GROUP BY (lastname, firstname);

DROP TABLE user_tbl;

ALTER TABLE tmp RENAME TO user_tbl;
pdtvr36n

pdtvr36n8#

显示记录

SELECT `page_url`,count(*) FROM wl_meta_tags GROUP BY page_url HAVING count(*) > 1

删除记录

DELETE FROM wl_meta_tags 
WHERE meta_id NOT IN( SELECT meta_id 
FROM ( SELECT MIN(meta_id)AS meta_id FROM wl_meta_tags GROUP BY page_url HAVING COUNT(*) > 1 )AS a ) 
AND meta_id NOT IN( (SELECT ids FROM (
SELECT MIN(meta_id)AS ids FROM wl_meta_tags GROUP BY page_url HAVING COUNT(*) =1 )AS a1 ) )

Source url

3pvhb19x

3pvhb19x9#

WITH CTE AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY [emp_id] ORDER BY [emp_id]) AS Row, * FROM employee_salary
)

DELETE FROM CTE
WHERE ROW <> 1

相关问题