我可以使用我用于选择删除的相同内连接查询还是有特定的?

时间:2016-09-27 11:38:30

标签: mysql

我用它来选择我需要的所有图片,而不是用一些代码移动它们。

SELECT estate_pictures.picture
FROM estate_pictures 
INNER JOIN estate 
ON estate_pictures.estate_id=estate.id 
WHERE estate.neighborhood 
IN (56,57,64,67,68,69,71,73,77,81,83,84,85,86,87,95,96,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,118,119,120,121,122,123,124,125,127,128,129,130,131,132)

之后我想删除所有出现的行:

SELECT * 
FROM estate_pictures 
INNER JOIN estate 
ON estate_pictures.estate_id=estate.id 
WHERE estate.neighborhood 
IN (56,57,64,67,68,69,71,73,77,81,83,84,85,86,87,95,96,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,118,119,120,121,122,123,124,125,127,128,129,130,131,132)

只是将“DELETE”而不是“SELECT *”工作,或者还有更多要改变才能工作。我还不清楚如何备份数据库,所以我想确保它在我执行DELETE查询之前有效。它不像SELECT那些。 I.E.这会有用吗?

DELETE
FROM estate_pictures 
INNER JOIN estate 
ON estate_pictures.estate_id=estate.id 
WHERE estate.neighborhood 
IN (56,57,64,67,68,69,71,73,77,81,83,84,85,86,87,95,96,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,118,119,120,121,122,123,124,125,127,128,129,130,131,132)

2 个答案:

答案 0 :(得分:0)

是的,这应该有效。只需使用DELETE而不是SELECT *,这应该可行。

答案 1 :(得分:0)

您应该指定表格。我猜你要从estate_pictures删除:

DELETE ep 
FROM estate_pictures ep INNER JOIN
     estate e
ON ep.estate_id = e.id 
WHERE e.neighborhood 
IN (56,57,64,67,68,69,71,73,77,81,83,84,85,86,87,95,96,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,118,119,120,121,122,123,124,125,127,128,129,130,131,132);

您也可以从estate删除,但我猜这不是意图。

而且,通常最好将要删除的记录复制到临时表中。然后,使用这些记录插入另一个表相同的临时表中进行删除。这可以防止在两个操作之间修改数据库而导致的任何问题。

编辑:

要从两个表中删除,只需将它们包含在DELETE表列表中:

DELETE ep, e
FROM estate_pictures ep INNER JOIN
     estate e
ON ep.estate_id = e.id 
WHERE e.neighborhood 
IN (56,57,64,67,68,69,71,73,77,81,83,84,85,86,87,95,96,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,118,119,120,121,122,123,124,125,127,128,129,130,131,132);