以下是我要做的事情:
从projects
表中删除项目以及images
表中与该项目关联的所有图像。
让我们说$del_id = 10
DELETE FROM projects, images WHERE projects.p_id = '$del_id' AND images.p_id = '$del_id'
此查询有什么问题?
答案 0 :(得分:4)
$sql = "DELETE FROM projects, images WHERE projects.p_id = '".$del_id."' or images.p_id = '".$del_id."'";
删除时,项目永远不会满足这两个要求,因此必须OR
而不是AND
答案 1 :(得分:4)
作为Chacha102 noted,您的查询问题是AND
子句中的WHERE
。
但是,您可能希望将JOIN
语法用于多表DELETE
,我觉得这更容易阅读:
DELETE projects, images
FROM projects
LEFT JOIN images ON images.p_id = projects.p_id
WHERE projects.p_id = 10;
答案 2 :(得分:3)
DELETE projects, images
FROM projects, images
WHERE projects.p_id = '$del_id'
AND projects.p_id = images.p_id;
答案 3 :(得分:2)
<?php
$query = sprintf("
DELETE FROM p, i
USING projects p, images i
WHERE p.p_id = %d
AND p.p_id = i.p_id
", $del_id);
?>
create table projects (
p_id int unsigned not null auto_increment primary key
);
insert into projects (p_id) values (1),(2),(3);
select * from projects;
-- +------+
-- | p_id |
-- +------+
-- | 1 |
-- | 2 |
-- | 3 |
-- +------+
create table images (
i_id int unsigned not null auto_increment primary key,
p_id int unsigned default null
);
insert into images (p_id) values (1),(1),(1),(2),(2),(3),(3);
select * from images;
-- +------+------+
-- | i_id | p_id |
-- +------+------+
-- | 1 | 1 |
-- | 2 | 1 |
-- | 3 | 1 |
-- | 4 | 2 |
-- | 5 | 2 |
-- | 6 | 3 |
-- | 7 | 3 |
-- +------+------+
delete from p, i
using projects p, images i
where p.p_id = i.p_id
and p.p_id = 1;
select * from projects;
-- +------+
-- | p_id |
-- +------+
-- | 2 |
-- | 3 |
-- +------+
select * from images;
-- +------+------+
-- | i_id | p_id |
-- +------+------+
-- | 4 | 2 |
-- | 5 | 2 |
-- | 6 | 3 |
-- | 7 | 3 |
-- +------+------+
答案 4 :(得分:0)
您应该使用两个单独的查询来执行此操作:
delete from images where p_id = 123;
delete from projects where p_id = 123;
即。 :
并且,作为安全预防措施,您应该将所有这些包装在一个事务中,以获得全部或全部行为 - 好吧,如果您使用的是支持事务的存储引擎,例如InnoDb。
请参阅MySQL手册中的12.3.1. START TRANSACTION, COMMIT, and ROLLBACK Syntax。
答案 5 :(得分:0)
将AND更改为OR。
您可能希望使用带有级联删除的外键约束,这样更容易,但您必须使用innoDB并创建此FK约束。删除项目,所有相关图像也将被删除。
答案 6 :(得分:-1)
(错误答案,MySQL allows this)
您无法从一个查询中的两个表中删除。
最接近的是在事务中包装两个删除:
begin transaction
delete from projects where p_id = $del_id
delete from images where p_id = $del_id
commit transaction