2016-09-20 67 views
0

如果flag字段中的值爲4,我試圖刪除記錄的所有實例。 (這意味着他們從郵件列表退訂)如果滿足條件,則刪除記錄的所有實例

的樣本數據:

Customer#  Email   Name CustomerType Flag 
    001  [email protected] Bob  Vet   1 
    001  [email protected] Bob  Med   2 
    001  [email protected] Bob  Pod   4 

那麼既然有此記錄爲4一個Flag,所有3個應該從這個查詢中移除一個實例。他們不需要真正從數據庫中刪除,我只是不需要在我的查詢中出現數據。我如何解決這個問題?

回答

3

假設客戶號是記錄什麼聯繫在一起,你可以使用一個not exists條款:

select * 
    from tbl t1 
where not exists (select * 
        from tbl t2 
        where t2.[Customer#] = t1.[Customer#] 
        and t2.Flag = 4) 
+0

感謝sstan,我相信這對我很有用。我感謝幫助! – Charles

2

這裏有一個方法:

delete from sample 
    where customer# in (select customer# from sample as s2 where flag = 4); 

編輯:

你可以很容易適應這個select

select s.* 
from sample s 
where customer# not in (select customer# from sample as s2 where flag = 4); 
+0

我相信你錯過了這一點:「他們不需要真正從數據庫中刪除」 – xQbert

+0

@xQbert。 。 。謝謝,我確實想念那個。 –

+0

感謝您的迴應! – Charles

2

三種方法。

  1. 使用不存在
  2. 使用其中不
  3. 使用連接

下面是連接:Sstan提供的不存在,戈登,但變化或多或少地提供了哪裏不在和選擇,你也有。

沒有表格大小的翻譯量和索引信息我不能說哪個會提供最好的表現,儘管不存在是強烈的喜愛。

SELECT A.* 
FROM TableName A 
LEFT JOIN TableName B 
on A.Customer# = B.Customer# 
and B.Flag = 4 
WHERE B.Customer# is null 

這會自我連接,但只會對一組標記爲4的記錄進行自我連接,然後排除那些具有匹配的記錄;只返回客戶#沒有4.

+0

感謝您的信息!這對解決這個問題非常有幫助。 – Charles

相關問題