简体   繁体   中英

MySQL doesn't let me delete record

I'm trying to do this MySQL clause from PHP

$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "DELETE FROM table_2 WHERE id in (select DISTINCT(id) FROM table_2 WHERE id NOT IN (SELECT id FROM table_2 WHERE p = 1 AND r =1))";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}

I get the following error

Error deleting record: You can't specify target table 'table_2' for update in FROM clause

What am I doing wrong?

You can bypass this limitation of MySQL with a subquery, but your statement can be simplified like this:

DELETE FROM table_2 
WHERE id NOT IN (
  SELECT id FROM (
    SELECT id FROM table_2 WHERE p = 1 AND r = 1
  ) t
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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