简体   繁体   English

SQL查询删除多行

[英]SQL query to delete multiple rows

How we can delete multiple rows having columns from a db? 我们如何删除db中包含列的多行? Suppose db has following data (id, list_name, user) and list_name has values as: 假设db具有以下数据(id,list_name,user),list_name具有以下值:

 Owner-aaa
 coowner-aaa
 owner-aaa
 subowner-aaa

How we can delete the rows having "Owner-aaa" and "owner-aaa" which are duplicates? 我们如何删除具有“Owner-aaa”和“owner-aaa”的重复行?

Can we add something in this query here: 我们可以在此查询中添加一些内容:

delete from <table_name> where list_name = 'owner-aaa'

But it deletes only lower case list, I want something general which checks duplicates in small and caps and delete both of them? 但它只删除小写列表,我想要一些通用的检查重复小和大写并删除它们?

Thanks in advance Amy 在此先感谢艾米

delete from tableName where LOWER(list_name) = 'owner-aaa'
DELETE FROM mytable WHERE LOWER(listname) IN
(SELECT LOWER(listname) FROM mytable 
GROUP BY LOWER(listname)
HAVING COUNT(*) > 1)
DELETE a
FROM list a
INNER JOIN list b ON LOWER(a.list_name)=LOWER(b.list_name)
WHERE a.id <> b.id

Meaby you can use LOWER/UPPER sql functions. Meaby你可以使用LOWER / UPPER sql函数。

But are you sure your model is correct? 但你确定你的模型是正确的吗? It seem realy weird to have a name list like that. 拥有这样的名单似乎真的很奇怪。 That should be another table NAMES with ID and NAME field. 这应该是具有ID和NAME字段的另一个表名。 It's a 1-N relation. 这是一个1-N的关系。

I'm not entirely sure from your question whether you want to delete all rows where duplicates occur, or leave one, and remove only the true duplicates. 我不完全确定您是否要删除发生重复的所有行,或者保留一个,并仅删除真正的重复项。 So here's a shot at each: 所以这里有一个镜头:

To remove only the true duplicates: 要仅删除真正的重复项:

DELETE FROM MyTable WHERE id IN
(
   SELECT T1.id 
     FROM MyTable T1
          INNER JOIN MyTable T2
             ON UPPER(T1.list_name) = UPPER(T2.list_name)
            AND T2.id <> T1.id
            AND (T1.id <> (SELECT MAX(id) FROM MyTable WHERE UPPER(list_name) = UPPER(T1.list_name))
) DUPS

This presumes that the id field is unique to each record 这假定id字段对于每个记录是唯一的

To remove all records where there are duplicates, remove the two "AND" clauses in the subquery. 要删除存在重复项的所有记录,请删除子查询中的两个“AND”子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM