如何在SQL中删除ID为(x到y)的多行


86

我正在尝试运行SQL查询以删除表中ID为163到265的行

我试图这样做以减少行数

    DELETE FROM `table` WHERE id IN (264, 265)

但是,一次要删除100行时,是否有类似于上述方法的查询,我也试图使用这种查询,但执行失败

    DELETE FROM `table` WHERE id IN (SELECT * FROM table WHERE id = )

请告诉我查询以执行上述操作...



这是不是一个从上面提到复制......其他涉及到缺失consecutives的范围内,在这个问题指的是可能的非连续的ID的,ID列表..缺失
天璇马雷

Answers:


186

如果需要基于列表删除,可以使用IN

DELETE FROM your_table
WHERE id IN (value1, value2, ...);

如果您需要根据查询结果删除,也可以使用IN

DELETE FROM your_table
WHERE id IN (select aColumn from ...);

(请注意,子查询只能返回一列)

如果您需要基于一系列值删除,请使用BETWEEN或使用不等式:

DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;

要么

DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;

1
谢谢!我已经使用BETWEEN并成功执行了它。
balu zapps

10
@baluzapps如果您认为此答案有用,请接受;)
Barranka 2014年

一个与此有关的问题:如果我有复合密钥怎么办?
Mayur Beldar

1
@MayurBeldar:如果您有新问题,请将其发布为问题而不是评论
Barranka '18

21

您可以使用BETWEEN

DELETE FROM table
where id between 163 and 265

2

请尝试以下方法:

DELETE FROM `table` WHERE id >=163 and id<= 265

1
Delete Id from table where Id in (select id from table)

2
您能通过突出显示代码并按Ctrl + K来格式化代码吗?
WhatsThePoint

4
我认为这不是delete声明的正确语法
Fabrizio

-6
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]       
@CODE XML
,@ERRFLAG  CHAR(1) = '0' OUTPUT    

AS        

SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  

DELETE tb_SampleTest
    WHERE 
        CODE IN(
            SELECT Item.value('.', 'VARCHAR(20)')
            FROM  @CODE.nodes('RecordList/ID') AS x(Item)
            )

IF @@ROWCOUNT = 0
    SET @ERRFLAG = 200

SET NOCOUNT OFF

获取字符串值删除

<RecordList>
    <ID>1</ID>
    <ID>2</ID>
</RecordList>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.