简体   繁体   English

MySQL检查行是否存在并在同一查询中将其删除

[英]MySQL check if rows exists and delete it in the same query

I would like to do the following in one query, I was wandering if it is even possible: 我想在一个查询中执行以下操作,即使有可能,我也在徘徊:

$rowsQ = $mysql->query("SELECT * FROM `table` WHERE (a='a' AND b='b')");
if($rowsQ->num_rows){
    $mysql->query("DELETE FROM `table` WHERE (a='a' AND b='b')");
}

I have seen a similar thing with WHERE EXISTS but only with a query for a different table like so: 我在WHERE EXISTS中看到了类似的情况,但是只查询了一个不同的表,如下所示:

$mysql->query("DELETE FROM `table` WHERE EXISTS (SELECT * FROM `table2` WHERE table.id = table2.id)");

Is it possible to do on the same table though and if so do I have to rewrite the same conditions or is there a shorter way? 是否可以在同一张表上进行操作,如果需要,我必须重写相同的条件,还是有一种更短的方法?

you can simply use DELETE , in case row doesn't exists with the specified values, the query would return with out doing any thing. 您可以简单地使用DELETE ,以防不存在具有指定值的行,查询将不做任何事情而返回。 you can avoid the select 你可以避免select

DELETE FROM table WHERE a ='a' and b='b'

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

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