如何将两个 PDO 查询合并为一个?
我有两个名为 users
和 contacts
的表。我想一次删除两个表中的记录。为此,我现在使用下面的代码。
public function delete($userId, $contactId) {
/* Since Values cannot be mixed (the Numbers) with control flow logic
(the commas) with prepared statements needs one placeholder per Value. */
//As many question marks as array entries; the last one needs no comma
$questionMarks = str_repeat("?,", count($userId)-1)."?";
$sth = $this->dbh->prepare("DELETE FROM users WHERE id IN($questionMarks)");
$sth->execute($userId);
$questionMarks = str_repeat("?,", count($contactId)-1) . "?";
$sth = $this->dbh->prepare("DELETE FROM contacts WHERE id IN($questionMarks)");
$sth->execute($contactId);
}
请注意,$userId
和 $contactId
将是一个数组,并且计数始终相等。
如何将这两个查询合并为一个?
答案:
以下查询对我有用。
DELETE users,contacts FROM users INNER JOIN contacts WHERE users.id IN (2) AND contacts.id IN (2);
I have two tables named users
and contacts
. I would like to delete the records from two table at once. For that I am using the code below for now.
public function delete($userId, $contactId) {
/* Since Values cannot be mixed (the Numbers) with control flow logic
(the commas) with prepared statements needs one placeholder per Value. */
//As many question marks as array entries; the last one needs no comma
$questionMarks = str_repeat("?,", count($userId)-1)."?";
$sth = $this->dbh->prepare("DELETE FROM users WHERE id IN($questionMarks)");
$sth->execute($userId);
$questionMarks = str_repeat("?,", count($contactId)-1) . "?";
$sth = $this->dbh->prepare("DELETE FROM contacts WHERE id IN($questionMarks)");
$sth->execute($contactId);
}
Please note that $userId
and $contactId
will be an array and the count will always be equal.
How do I merge these two queries into one?
ANSWER :
The below query worked for me.
DELETE users,contacts FROM users INNER JOIN contacts WHERE users.id IN (2) AND contacts.id IN (2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的说法,这个问题的答案不在于您的 pHp 语句,甚至不在您的查询中,而在于您如何在数据库中创建表。
创建表时,您必须指定外键关系,然后 ON DELETE CASCADE 将解决所有引用问题,当删除父行时,所有具有 ON DELETE CASCADE 的引用行也将被删除。已删除。
您的联系人 sql 中可能会出现这样的情况。
因此,根据您使用的数据库,
The answer to this question lies, according to me, Not in your pHp statements or even in your query but in HOW you created your tables in database.
When you created your table you must have specified a FOREIGN KEY relationship and then an ON DELETE CASCADE will solve all the reference problems when the parent row is deleted all the refering rows with the ON DELETE CASCADE will also be deleted.
so it may be something like this in your sql for contacts
depending on the database you use.
您需要找到将表连接在一起并使用类似查询的方法
You need to find the way to join the tables together and use a query like