将select和delete查询作为单个语句

时间:2013-12-26 10:30:46

标签: mysql sql select join sql-delete

第一次查询

    select id from posts where post_title='abc' || post_title='xyz' order by id desc limit 1;

假设返回值为730和735。

下一个查询

    delete from posts where id in(730,735);

我希望将这两个查询合并为一个语句。怎么做到呢。请帮忙

我在下面尝试了这个。它不起作用。

delete from posts where id in
        (
            select id from posts where post_title='abc' order by id desc limit 1,
                            select id from posts where post_title='xyz' order by id desc limit 1
                        );

6 个答案:

答案 0 :(得分:2)

在我看来,我们必须在一个查询中执行delete-and-select时使用 IF-EXISTS 子句,因为如果select返回null,它将抛出异常,所以试试这个:

IF EXISTS (SELECT id FROM [Posts] WHERE post_title IN ('abc', 'xyz'))
BEGIN 
     DELETE FROM posts 
     WHERE id IN (SELECT id 
                  FROM [Posts]
                  WHERE post_title IN ('abc', 'xyz') 
                  ORDER BY post_title, id DESC
                 ) 
END

答案 1 :(得分:1)

试试这个:

DELETE FROM posts 
WHERE id IN (SELECT id 
             FROM (SELECT post_title, MAX(id) id 
                   FROM posts 
                   WHERE post_title IN ('abc', 'xyz') 
                   GROUP BY post_title 
                  ) A 
            )

DELETE FROM posts 
WHERE id IN (SELECT id 
             FROM (SELECT post_title, id 
                   FROM posts 
                   WHERE post_title IN ('abc', 'xyz') 
                   ORDER BY post_title, id DESC
                 ) A 
            GROUP BY post_title)

答案 2 :(得分:0)

试试这个:

delete from posts where id in (
    select * from
    (
       select id from posts 
       where post_title='abc' or post_title='xyz'
    ) as t
);

您必须将其包装在别名中。

答案 3 :(得分:0)

作为您问题的解决方案,请尝试执行以下sql查询

delete FROM `posts` WHERE  id in 
(select p.id from 
                 (select id from posts where title in('abc','xyz') p)

答案 4 :(得分:0)

正如here

所解释的那样

在MySQL中,您无法修改在SELECT部分​​中使用的同一个表。

如果你绝对需要子查询,那就有一个解决方法,但由于几个原因,包括性能,它很难看:

delete from posts where id in
(
  select id from (select * from posts)as x 
  where post_title = 'xyz' or
        post_title = 'abc'
  order by id desc
);

请参阅here in action

在您的实际代码中添加限制1 ,在线版本不支持。

答案 5 :(得分:0)

试试这个

DELETE FROM [posts]
WHERE id = ANY( SELECT id FROM [posts] WHERE post_title IN('abc','xyz') );