2010-12-06 79 views
2

我想刪除banners的任何行,如果沒有相應的行banners_pp刪除一行

我做的怎麼辦{doesn't exist}部分?

DELETE banners.* FROM banners 
LEFT JOIN banners_pp 
USING(banner_id) 
WHERE banners_pp.banner_id {doesn't exist} 
+1

您應該使用外鍵在未來避免刪除孤立行。 – 2010-12-06 12:11:40

回答

1
DELETE FROM banners 
WHERE NOT EXISTS (
    SELECT * 
    FROM banners_pp 
    WHERE banner_id = banners.banner_id 
) 

看到more細節

0
DELETE 
FROM banners 
WHERE NOT EXISTS (SElect 1 from banners_pp 
      WHERE banners_pp.banner_id = banners.banner_id) 
0

試試這個

DELETE FROM banners 
WHERE banner_id NOT IN (
SELECT banner_id 
FROM banners_pp 
) 
0
DELETE FROM banners b 
WHERE NOT EXISTS (
    SELECT * 
    FROM banners_pp bp 
    WHERE bp.banner_id = b.banner_id 
) 
1

使用WHERE banners_pp.banner_id IS NULL

LEFT JOIN中,左表(banners)中右表中沒有對應行的行(banners_pp)存在,但在右表的列中有NULL。如果在有banner_id = 2banners_pp沒有進入,但在bannersbanner_id = 2的條目,在連接表中的對應行可能看起來有點像這樣:

| banners.banner_id | banners.foo | banners_pp.banner_id | banners_pp.bar | 
|   2   |  x  |   NULL   |  NULL |