简体   繁体   中英

php\mysql delete data from two not related table in one query

i have to table tbl1 and tbl2 and there is no relation between them, i want to delete different data from both table using one query is that possible or should i do it in two separate query

i tried the following query

$del =" 
DELETE 
  FROM tbl1
    , tbl2 
 WHERE tbl1.delete_time IS NOT NULL
   AND tbl1.delete_time != '0000-00-00 00:00:00' 
   AND tbl2.delete_time IS NOT NULL 
   AND tbl2.delete_time != '0000-00-00 00:00:00'
";                   
$sql =mysql_query($del) or die(mysql_error());
$res = mysql_query($sql);

but i got the following error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE tbl1.delete_time IS NOT null AND tbl1.delete_time != '0000-0' at line 1

thanks in advance

Consider changing your query by separating them with ; like below

DELETE FROM tbl1 WHERE delete_time IS NOT null AND delete_time != '0000-00-00 00:00:00'; DELETE FROM tbl2 WHERE delete_time IS NOT NULL AND delete_time != '0000-00-00 00:00:00'; 

(OR) Recommended way; Wrap both the DELETE statement in a stored procedure like

create procedure usp_deleteData
as
begin
    DELETE FROM tbl1 
    WHERE delete_time IS NOT null 
    AND delete_time != '0000-00-00 00:00:00'; 

    DELETE FROM tbl2 
    WHERE delete_time IS NOT NULL 
    AND delete_time != '0000-00-00 00:00:00'; 
end

Also, though you have no relationship between the tables but you have common column named delete_time and so you can perform a Multi Table DELETE-JOIN like

DELETE tbl1, tbl2 FROM tbl1 
INNER JOIN tbl2 
WHERE tbl2.delete_time = tbl1.delete_time
AND tbl2.delete_time IS NOT NULL
AND tbl1.delete_time IS NOT NULL
AND '0000-00-00 00:00:00' NOT IN (tbl1.delete_time, tbl2.delete_time);

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