简体   繁体   English

MySQL 在一个查询条件中删除多行,每一行都是唯一的

[英]MySQL delete multiple rows in one query conditions unique to each row

So I know in MySQL it's possible to insert multiple rows in one query like so:所以我知道在MySQL 中可以在一个查询中插入多行,如下所示:

INSERT INTO table (col1,col2) VALUES (1,2),(3,4),(5,6)

I would like to delete multiple rows in a similar way.我想以类似的方式删除多行。 I know it's possible to delete multiple rows based on the exact same conditions for each row, ie我知道可以根据每行完全相同的条件删除多行,即

DELETE FROM table WHERE col1='4' and col2='5'

or要么

DELETE FROM table WHERE col1 IN (1,2,3,4,5)

However, what if I wanted to delete multiple rows in one query, with each row having a set of conditions unique to itself?但是,如果我想在一个查询中删除多行,并且每行都有一组独特的条件怎么办? Something like this would be what I am looking for:像这样的东西将是我正在寻找的:

DELETE FROM table WHERE (col1,col2) IN (1,2),(3,4),(5,6)

Does anyone know of a way to do this?有谁知道这样做的方法? Or is it not possible?或者不可能?

You were very close, you can use this:你非常接近,你可以使用这个:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle .请看这个小提琴

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.对给出的答案的轻微扩展,因此,希望对提问者和其他任何人都有用。

You can also SELECT the values you want to delete.您还可以SELECT要删除的值。 But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.但要注意错误 1093 - 您不能在 FROM 子句中指定要更新的目标表。

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000.我想删除单个操作/分支的历史记录数超过 10,000 的所有历史记录。 And thanks to this question and chosen answer, I can.感谢这个问题和选择的答案,我可以。

Hope this is of use.希望这是有用的。

Richard.理查德.

Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.进行了大量的谷歌搜索,但是当我想使用值列表从单个表中删除多个项目时,这是我在 Python 中为 MySql 所做的。

#create some empty list
values = []
#continue to append the values you want to delete to it
#BUT you must ensure instead of a string it's a single value tuple
values.append(([Your Variable],))
#Then once your array is loaded perform an execute many
cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)

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

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