2013-09-30 38 views
1

我曾與下面的SQL查詢的一個問題:SQL錯誤:DELETE,然後從衝突

DELETE FROM table1 WHERE uid = 
(SELECT table1.uid from table1 INNER JOIN table2 ON table2.user = table1.uid 
INNER JOIN table3 ON table3.uid = table2.seminar WHERE table3.end_date < CURDATE())) 

的錯誤是: 您不能指定目標表「表1」的更新在FROM子句

有沒有人有一個想法如何解決這個問題?

+0

標識表1似乎是ambigious,因爲你在你的外部查詢('DELETE')使用它,以及在內部查詢,你需要給它一個別名在內部查詢中,並在您的條件下使用它來使其工作 – DrCopyPaste

回答

0

試試這個: -

DELETE table1 FROM table1 INNER JOIN table2 ON table2.user = table1.uid 
     INNER JOIN table3 ON table3.uid = table2.seminar 
WHERE table3.end_date < CURDATE() 
+0

在格式化你的答案之前,嗯格式化看起來很有趣 –

+0

只是想快點,但你贏了秒鐘;) –

+0

你們倆都很好解決......謝謝你的回答!現在它工作了!非常感謝你們! – Adrian

1

您可以選擇加入表格。

DELETE table1 
FROM table1 
     INNER JOIN table2 
      ON table2.user = table1.uid 
     INNER JOIN table3 
      ON table3.uid = table2.seminar 
WHERE table3.end_date < CURDATE() 
+0

[看着你的評論](http://stackoverflow.com/questions/19098279/sql-error-delete-and-select-from-conflict/19098331 #comment28236629_19098331)您需要使用'FIND_IN_SET()',因爲這些值以逗號分隔。例如'WHERE table3.end_date 0 AND FIND_IN_SET('69',table1.group)> 0 )'如果'table1.group'之間有空格,你也需要刪除它。例如。 'FIND_IN_SET('67',REPLACE(table1.group,'','')> 0' –

2

這可能不是最優雅的方式,但你可以選擇你的標準到一個臨時表,然後DELETE FROM其中#MyTempTable

SELECT table1.uid 
INTO #MyTemp 
from table1 INNER JOIN table2 ON table2.user = table1.uid 
INNER JOIN table3 ON table3.uid = table2.seminar WHERE table3.end_date < CURDATE()) 


DELETE FROM table1 
WHERE uid IN 
(SELECT uid from #MyTemp) 

DROP TABLE #MyTemp 
0

我的首選語法是:

Delete deleteAlias 
/* Select *   */ 
from table1 deleteAlias 
where exists (select null from table1 innerTable1 INNER JOIN table2 ON table2.user = innerTable1.uid 
INNER JOIN table3 ON table3.uid = table2.seminar WHERE table3.end_date < CURDATE()) 

AND deleteAlias.uid = innerTable1.uid 

    ) 

如果這種方法是微妙的好處,您可以用一個簡單的「select *」來替換運行刪除之前將刪除的內容。

/* Delete deleteAlias */ 
Select * 
from table1 deleteAlias 
where exists (select null from table1 innerTable1 INNER JOIN table2 ON table2.user = innerTable1.uid 
INNER JOIN table3 ON table3.uid = table2.seminar WHERE table3.end_date < CURDATE()) 

AND deleteAlias.uid = innerTable1.uid 

    ) 
+0

所有的T1和T2都開始一起運行。通過爲「外部」表提供一個明確的別名(本例中爲table1 deleteAlias),當您使用exists子句時,您可以清楚地看到「存在子句內部」連接到「存在子句外部」....(「 AND deleteAlias.uid = innerTable1.uid「)。請記住,軟件開發的更大成本是〜維護〜,而不是初始創建.......... aka,有人需要能夠看到你在路上做了什麼........甚至如果那個人是你。 – granadaCoder