[英]How can I delete multiple rows from a table with another condition?
I have a table like this:我有一张这样的桌子:
Id Name ProductId
1 Apple 1
2 Apple null
3 Apple 2
4 Orange 1
5 Orange 2
6 Pear null
7 Lemon 1
8 Lemon null
I want to delete a row if it's ProductId is null
and if it's Name
is occurs more than once.如果它的ProductId is null
并且如果它的Name
出现不止一次,我想删除一行。
At this example if I run a proper delete query, it should delete these rows:在这个例子中,如果我运行一个正确的删除查询,它应该删除这些行:
2 Apple null
8 Lemon null
Which kind of delete query can work for me?哪种删除查询适合我?
I would recommend using aggregation or something similar before joining:我建议在加入之前使用聚合或类似的东西:
delete t from test t join
(select t.name, count(*) as cnt
from test t
group by t.name
) tt
on t.name = tt.name
where tt.cnt > 1 and t.product_id is null;
This is much better than a self join without aggregation.这比没有聚合的自连接要好得多。 Why?为什么? Because each row is identified exactly once.因为每一行都被标识一次。 In your sample data, a self-join without aggregation attempts to delete row id = 2 twice (once for the match to 1 and once for the match to 3).在您的示例数据中,没有聚合的自联接尝试删除行 id = 2 两次(一次用于匹配 1,一次用于匹配 3)。 That is unnecessary.那是不必要的。 And it can become highly inefficient if a name
has many rows.如果name
有很多行,它可能会变得非常低效。
I also think that you don't simply want a cnt of 2 but you want a non- NULL
product id.我还认为您不只是想要一个 2 的 cnt,而是想要一个非NULL
产品 ID。 That is:那是:
delete t from test t join
(select t.name, count(*) as cnt
from test t
where product_id is not null
group by t.name
) tt
on t.name = tt.name
where tt.cnt >= 1 and t.product_id is null;
DELETE t
FROM test t
INNER JOIN test t2
ON t.name = t2.name
WHERE
t.product_id is null
AND t2.id <> t.id
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e58dc760d30bfaec4e46be7c80729200 https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e58dc760d30bfaec4e46be7c80729200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.