2011-06-01 68 views
0

我使用MySQL:入世對缺失

  • btableA有tableB_id列
  • tableB的具有some_interestring_column_on_TableB

我想要的(僞以下SQL):

delete from tableA 
where the associated row in tableB (via tableB_id) has 
    some_interestring_column_on_TableB = 'interestingValue' 

請幫助我將僞sql轉換爲真正的sql。

回答

2

MySQL supports JOINs in the DELETE statement, as well as deleting from multiple tables in a single statement。下面將只能從TABLEA刪除:

DELETE ta 
    FROM TABLEA ta 
    JOIN TABLEB tb ON b.id = a.tableb_id 
       AND b.col = 'some value' 

如果你想從兩個表,使用刪除:

DELETE ta, tb 
    FROM TABLEA ta 
    JOIN TABLEB tb ON b.id = a.tableb_id 
       AND b.col = 'some value' 

這就是說,這種支持是其他數據庫中非常少見 - 你必須在大多數情況下使用INEXISTS

3

試試這個:

DELETE TableA 
WHERE tableB_id IN (
    SELECT id FROM TableB 
    WHERE interestring_column='pizza'); 
+0

不錯,你打我吧! – Brett 2011-06-01 02:37:06

+0

不錯,但是如果tableB比tableA大得多,或者interesting_column沒有索引 – shealtiel 2011-06-01 02:39:04

+1

@gid:無論你來到哪裏,如果你沒有索引,你的性能會很差。 'IN'非常快。可以爭論'LEFT JOIN'是否會更快。你說這是低效的。你有基準嗎?爲什麼*不是*如果你知道它會提高性能,那麼就有索引。 *如果沒有正確的索引,調整和數據庫統計信息,任何*都將是低效的。也許是 – 2011-06-01 02:41:15

0

我不知道MySQL的語法,但我想這樣(從MSSQL):

delete from tableA 
where tableA.tableB_id in 
    (select tableB.id from tableB 
    where tableB.some_interesting_column_on_TableB = 'interestingValue')