简体   繁体   English

MySQL从多个表中删除行

[英]MySQL Delete rows from multiple tables

I have 2 tables users and pd having a common column i_uid 我有2个表用户,并且pd有一个公用列i_uid

For deleting from both the tables a single row having i_uid of 1010 I issued the following statement using mysqli::query in php script 为了从两个表中删除具有i_uid为1010的一行,我在php脚本中使用mysqli :: query发出了以下语句

DELETE 
FROM `users`,`pd`
WHERE `users`.`i_uid`=`pd`.`i_uid` AND `users`.`i_uid` = 1010;

Is there anything wrong? 有什么问题吗?

since you are deleting rows from multiple table, the only missing is to specify on what tables the row will be deleted, 由于您要从多个表格中删除行,因此唯一缺少的是指定要删除行的表格,

DELETE `users`,`pd`
FROM `users`, `pd`
WHERE `users`.`i_uid`=`pd`.`i_uid` AND `users`.`i_uid` = 1010;

in the query above, it will delete rows from both tables. 在上面的查询中,它将从两个表中删除行。 I suggest to change statement using ANSI join like below, 我建议使用ANSI联接来更改语句,如下所示,

DELETE  a, b 
FROM    users a
        INNER JOIN pd b
            ON a.i_uid = b.i_uid
WHERE  a.i_uid = 1010

if you want to delete from users table, 如果要从users表中删除,

DELETE  a
FROM    users a
        INNER JOIN pd b
            ON a.i_uid = b.i_uid
WHERE  a.i_uid = 1010

Use Left Join and specify the tables on which corresponding rows will be deleted. 使用“ Left Join并指定要在其上删除相应行的表。

DELETE users, pd
FROM users, pd
LEFT JOIN pd
ON pd.i_uid = users.i_uid
WHERE users.i_uid = 1010

Other answers are correct but since no one mentioned it I will. 其他答案是正确的,但由于没有人提及,我会这样做。 You could use InnoDB engine and specify foreign keys and DELETE ON CASCADE . 您可以使用InnoDB引擎并指定外键和DELETE ON CASCADE So that each time you delete a user it will delete all referencing rows from different tables. 这样,每次删除用户时,它都会从不同的表中删除所有引用行。

Read up on Foreign Keys and DELETE ON CASCADE 阅读有关外键的信息,并级联删除

To keep it simple I suggest using just two queries: 为了简单起见,我建议仅使用两个查询:

DELETE FROM `users` WHERE `i_uid` = 1010;
DELETE FROM `pd` WHERE `i_uid` = 1010;

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

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