如何从具有其他条件的 table 中删除多行?

How can I delete multiple rows from a table with another condition?

我有一个 table 这样的:

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

如果 ProductId is null 如果 Name 出现不止一次,我想删除一行。

在这个例子中,如果我运行一个正确的删除查询,它应该删除这些行:

2   Apple    null
8   Lemon    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

我建议在加入之前使用聚合或类似的东西:

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;

这比没有聚合的自连接要好得多。为什么?因为每一行都被标识了一次。在您的示例数据中,自连接 without 聚合尝试删除行 id = 2 两次(一次用于匹配 1,一次用于匹配 3)。那是不必要的。如果 name 有很多行,它会变得非常低效。

我还认为您不只是想要一个 2 的 cnt,而是想要一个非 NULL 的产品 ID。即:

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;

Here 是一个 db<>fiddle.