简体   繁体   English

从一个查询mysqli中的两个表中删除

[英]deleting from two tables in one query mysqli

I want to delete from two tables. 我想从两个表中删除。 I know I can use a join but I came across this post suggesting I could just do it like this with a semicolon: 我知道我可以使用联接,但是我发现这篇文章暗示我可以使用分号来做到这一点:

$query = "  DELETE from pupil_data WHERE pupil_id=$pupil_id;
            DELETE from pupil_conditions WHERE pupil_id=$pupil_id";
$bob = $conn->query($query);

This doesn't work. 这行不通。 If I do each query on their own then its fine. 如果我自己进行每个查询,那就好了。

Why doesn't it work with the semicolon? 为什么分号不起作用?

try like this 这样尝试

$query = "  DELETE from pupil_data WHERE pupil_id=$pupil_id;
            DELETE from pupil_conditions WHERE pupil_id=$pupil_id";
$bob = $conn->multi_query($query);

First of all, your query doesn't delete from two tables in one query. 首先,您的查询不会从一个查询的两个表中删除。 There are two separate SQL queries. 有两个单独的SQL查询。

Second, you don't need to run 2 queries in one function call. 其次,您不需要在一个函数调用中运行2个查询。 Run two separate queries in two separate function calls. 在两个单独的函数调用中运行两个单独的查询。 That would be logical and save you a lot of trouble. 这是合乎逻辑的,可以为您省去很多麻烦。

Third, never use mysqli_multi_query() for such a whim. 第三,切勿使用mysqli_multi_query()这样的想法。 This function's purpose is different. 此功能的目的不同。 Everyone who ask you to use it, never used it in reality and have no idea how to use it properly, helping you to shoot yourself in the foot. 要求您使用它的每个人,从来没有在现实中使用过它,也不知道如何正确使用它,从而可以帮助您射杀自己的脚。

Fourth, you ought to use prepared statements, instead of banging a variable in the query directly. 第四,您应该使用准备好的语句,而不是直接在查询中敲击变量。

$stmt = $conn->prepare("DELETE from pupil_data WHERE pupil_id=?");
$stmt->bind_param("s",$pupil_id);
$stmt->execute();

$stmt = $conn->prepare("DELETE from pupil_conditions WHERE pupil_id=?");
$stmt->bind_param("s",$pupil_id);
$stmt->execute();

is the code you have to run. 是您必须运行的代码。

DELETE table_1, table_2,... FROM table-refs [WHERE conditions] 删除table_1,table_2,... FROM table-refs [WHERE条件]
DELETE FROM table_1, table_2,... USING table-refs [WHERE conditions] 从table_1,table_2,...删除...使用table-refs [WHERE条件]

Here is the reference 这是参考

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

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