我的数据库中有5个表: Category1,Category2,Category3,Category4,Category5
我有一个可能在这些表上找到的用户。如果找到了,我想从桌子上删除他。
我可以用5个这样的查询来做到这一点:
//search if the user is already subscribed in every one of the categories
$stmt = $db->prepare("Select * FROM category1 WHERE deviceUDID = :deviceUDID");
$stmt->execute(array(':deviceUDID' => $deviceUDID));
if($rows_found = $stmt ->rowCount()) {
$stmt = $db -> prepare("DELETE FROM category1 WHERE deviceUDID =:deviceUDID");
$stmt->execute(array(':deviceUDID' => $deviceUDID));
}
然后对于category2:
//search if the user is already subscribed in every one of the categories
$stmt = $db->prepare("Select * FROM category2 WHERE deviceUDID = :deviceUDID");
$stmt->execute(array(':deviceUDID' => $deviceUDID));
if($rows_found = $stmt ->rowCount()) {
$stmt = $db -> prepare("DELETE FROM category1 WHERE deviceUDID =:deviceUDID");
$stmt->execute(array(':deviceUDID' => $deviceUDID));
}
其他类别的等等。
是否可以使用1个查询搜索所有这些类别以使其更快?
但是我无法看到这样的逻辑怎么会发生......任何想法?
每次只进行DELETE查询会更容易,更快还是更有效,即使用户不在那里并让查询失败?
或者我应该首先检查每个表,如果发现是否进行DELETE查询?
哪一种更有效?
答案 0 :(得分:2)
如果您担心原子性,那么在交易中附上5个删除就可以了。
或者,mysql现在应该支持外键和级联删除,所以如果你设置与“用户”表的外键关系,你可能没有更多的事情要做。
答案 1 :(得分:1)
没有。您可以创建一个视图,告诉您设备所在的类别,但它不可更新。
create view allCategories as
select 1 as category, *
from category1
union
select 2 as category, *
from category2
union
select 3 as category, *
from category3
union
select 4 as category, *
from category4
union
select 5 as category, *
from category5
答案 2 :(得分:1)
DELETE clause允许一个请求中有多个表。 试试:
DELETE FROM category1 c1, category2 c2, categorie3 c3 WHERE c1.deviceUDID= :deviceUDID AND c2.deviceUDID= :deviceUDID AND c3.deviceUDID= :deviceUDID ...
答案 3 :(得分:0)
DELETE FROM category1 WHERE deviceUDID in (Select * FROM category2 WHERE deviceUDID = :deviceUDID)
正是您要找的。 p>