几个MYSQL语句合二为一

时间:2017-12-07 20:19:44

标签: mysql sql

我有一个地方('地方')我可以有一些盒子('盒子')。在每个框中,我可以有项目('项目')。我也可以在盒子外面放置物品。 我想删除一个地方,然后删除该地方的每个方框,包括每个方框中的项目以及该地方的项目,但在任何方框外。 我得到了以下单独的陈述:

1:选择地点

SELECT placeid, placename 
FROM place 
WHERE userid = (SELECT id 
                FROM user 
                WHERE username = 'username' AND password ='password') 
  AND placename = 'placename'

2:选择该地方的方框

SELECT boxid, boxname 
FROM box 
WHERE placeid = 'id'

3a:对于每个方框,删除其中的项目

DELETE FROM item 
WHERE boxid = 'boxid'

3b:然后删除框

DELETE FROM box 
WHERE id = 'boxid'

4:删除不在框中的地方的项目

DELETE FROM item 
WHERE placeid = 'placeid' AND boxid = 0

5:删除地点

DELETE FROM place 
WHERE id = placeid

这是有效的,但当然这很慢。错误管理也不太适合使用。

有没有办法用更少的SQL语句或甚至只有一个来完成所有这些?

我当然在同一个陈述中删除了一个方框的问题!

编辑:使用php的mysql

非常感谢。

2 个答案:

答案 0 :(得分:1)

由于itembox都有一个placeid(根据您的问题中的信息),您可以稍微简化此任务,但仍需要3 DELETE个语句:

SELECT p.placeid
INTO #PlacesToDelete
FROM place p 
INNER JOIN [user] u ON p.userid = u.id
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'

DELETE i
FROM item i
INNER JOIN #PlacesToDelete ptd ON i.placeid = ptd.placeid

DELETE b
FROM box b
INNER JOIN #PlacesToDelete ptd ON b.placeid = ptd.placeid

DELETE p
FROM place p
INNER JOIN #PlacesToDelete ptd ON p.placeid = ptd.placeid

或者,如果这与MySQL有关,您应该能够进一步简化和使用单个语句:

DELETE p, b, i
FROM place p 
INNER JOIN [user] u ON p.userid = u.id
INNER JOIN box b ON b.placeid = p.placeid
INNER JOIN item i ON i.placeid = p.placeid
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'

修改:根据评论if an item is in a box, placeid is equal to 0 because it belongs to a box, not a place,这里有一个更新的查询,会删除您想要的所有内容:

DELETE i1, i2, b, p
FROM place p 
INNER JOIN [user] u ON p.userid = u.id
INNER JOIN box b ON b.placeid = p.placeid
INNER JOIN item i1 ON i1.placeid = p.placeid
INNER JOIN item i2 ON i2.boxid = b.boxid
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'

答案 1 :(得分:1)

你应该试试ON DELETE CASCADE,它看起来像这样:

ALTER TABLE box ADD CONSTRAINT fk_box_place_id 
                FOREIGN KEY (placeid) 
                REFERENCES place(id) 
                ON DELETE CASCADE;

ALTER TABLE item ADD CONSTRAINT fk_item_place_id 
                 FOREIGN KEY (placeid) 
                 REFERENCES place(id) 
                 ON DELETE CASCADE;

我认为您不需要任何其他级联,因为placeid在所有表格中都可用,并且会涵盖框内外的项目,但也许我忽视了某些内容。

设置完成后,您只需删除要删除的地点,其余部分将由您处理:

DELETE 
FROM place
WHERE placeID = 'deletedPlaceID';