2014-02-07 60 views
0

我想從表中刪除一些行。如何通過id刪除行,通過group_concat獲取

首先,我試圖使用子查詢,但在子查詢中使用同一個表時,我無法從表中刪除數據。

我試過用另一種方法做。

set @list_id_remove = (select group_concat(mra.media_id) from movie AS m 
right join media AS mra ON m.id = mra.media_id 
where m.id is null); 

delete from media 
where media_id IN (@list_id_remove); 

但在這種情況下查詢只刪除1行。 我覺得麻煩 - 是group_concat刪除字符串,我需要整數列表。

回答

3

你似乎想從media刪除其中對應的記錄不存在movie。您可以將其作爲單個查詢來完成。

delete from media 
    where not exists (select 1 from movie m where m.id = media.media_id); 

它似乎很奇怪,我該字段movie.id將對應於media.media_id,但那是你的原始查詢是怎麼寫的。

編輯:

至於你的問題,你可以寫delete爲:

delete from media 
    where find_in_set(media_id, @list_id_remove) > 0; 
+0

謝謝,第一個查詢的工作,但在此之前m.id = media.media_id – yAnTar

+0

添加查詢 「其中」一般服務器會聽到你的查詢更好,如果你[把握](http://stackoverflow.com/questions/9426138/why-are-the-queries-in-sql-mostly-written-in-capital-letters)代碼;) –

+0

@ yAnTar。 。 。謝謝。 –