我正在尝试使用inner join
删除2个表。我有一个modifier_category
表,它是父表,而modifier_items
表是子表。
它们相关的方式是modifier_categories
表主ID,存储在cat_id
列中与cat_parent_id
表中的modifier_items
匹配
我只能通过modifier_categories
查找item_id
表。
当我运行删除查询时,只有modifier_categories
表中的行被删除,但modifier_items
表中没有任何内容被删除。
以下是我正在使用的查询。我看了它至少一百次,并注意到似乎工作。
任何帮助都会非常感激。感谢先进的
DELETE mc
FROM modifier_categories mc
INNER JOIN modifier_items mi
ON mi.cat_parent_id=mc.cat_id
WHERE mc.menu_item_id = 28560
答案 0 :(得分:1)
架构:
drop table if exists people;
create table people
( id int primary key,
name varchar(100) not null,
gender char(1) not null
);
insert people (id,name,gender) values
(1,'Kathy','f'),(2,'John','m'),(3,'Paul','m'),(4,'Kim','m');
drop table if exists pets;
create table pets
( id int auto_increment primary key,
ownerId int not null,
name varchar(100) not null,
color varchar(100) not null,
foreign key `fk_pets_2_people` (ownerId) references people(id)
);
insert pets(ownerId,name,color) values
(1,'Rover','beige'),(2,'Bubbles','purple'),(3,'Spot','black and white'),
(1,'Rover2','white');
查询:
DELETE p1
FROM people p1
JOIN pets p2
ON p2.ownerId = p1.id
AND p1.name = 'Paul';
-- error 1451: FK violation (you would orphan poor Spot, left to feed himself)
-- and your constraint said not to do that
DELETE p2
FROM people p1
JOIN pets p2
ON p2.ownerId = p1.id
AND p1.name = 'Paul';
-- Spot is now gone
select * from pets;
+----+---------+---------+--------+
| id | ownerId | name | color |
+----+---------+---------+--------+
| 1 | 1 | Rover | beige |
| 2 | 2 | Bubbles | purple |
| 4 | 1 | Rover2 | white |
+----+---------+---------+--------+
然后重新加载数据。
DELETE p1,p2
FROM people p1
JOIN pets p2
ON p2.ownerId = p1.id
AND p1.name = 'Paul';
-- 2 rows deleted Spot is now gone
select * from people;
+----+-------+--------+
| id | name | gender |
+----+-------+--------+
| 1 | Kathy | f |
| 2 | John | m |
| 4 | Kim | m |
+----+-------+--------+
select * from pets;
+----+---------+---------+--------+
| id | ownerId | name | color |
+----+---------+---------+--------+
| 1 | 1 | Rover | beige |
| 2 | 2 | Bubbles | purple |
| 4 | 1 | Rover2 | white |
+----+---------+---------+--------+
正如问题评论中的示例所述,如果相关,请查看Cascade Deletes以了解您的具体情况。
您的查询(这是您打算做的吗?)
DELETE mi
FROM modifier_categories mc
INNER JOIN modifier_items mi
ON mi.cat_parent_id=mc.cat_id
WHERE mc.menu_item_id = 28560;
答案 1 :(得分:1)
好的,我找到了答案。我想要明确指定我想要删除的两个表。此代码有效
{{1}}
答案 2 :(得分:1)
从mc
表中删除记录(已加入的结果中)
DELETE mc
FROM modifier_categories mc
INNER JOIN modifier_items mi
ON mi.cat_parent_id=mc.cat_id
WHERE mc.menu_item_id = 28560
从mi
表中删除记录(已加入的结果中)
DELETE mi
FROM modifier_categories mc
INNER JOIN modifier_items mi
ON mi.cat_parent_id=mc.cat_id
WHERE mc.menu_item_id = 28560
要删除mc
和mi
表中的记录(已加入的结果中) 5月你正在寻找这个
DELETE mc,mi
FROM modifier_categories mc
INNER JOIN modifier_items mi
ON mi.cat_parent_id=mc.cat_id
WHERE mc.menu_item_id = 28560
请查看类似的post