2015-04-08 57 views
0

刪除重複行我有2個表:噸sql中從2個表

  • FirstTable
  • SecondTable

FirstTable具有這些列

sales_ID varchar(250) 
product_ID int 

SecondTable具有這些列

sales_ID varchar(250) 
product_ID int 
CreateDate datetime 

如果FirstTablesales_IDproduct_ID匹配SecondTablesales_Idproduct_ID,並且如果SecondTableCreatedDate是2015年4月7日,我需要從SecondTable

我試過這樣刪除的行:

delete from SecondTable 
WHERE sales_Id IN (SELECT sales_Id FROM FirstTable) 
    and product_ID IN (SELECT product_ID FROM FirstTable) 
    and CreatedDate = '07-04-2015' 

但是,它刪除所有行,並且它根據我想要的不正確(不工作)查詢。

如果product_ID等於product_ID和sales_ID等於sales_ID並且CreatedDate等於07.04.2015等於SecondTable,如何刪除重複行?

希望你明白我的壞英文

謝謝。

回答

1

試試這個:

delete from secondtable 
from secondTable st 
inner join firstTable ft on st.sales_id = ft.sales_id 
    and st.product_id = ft.product_id 
    and st.CreatedDate = '2015-07-04' 

注意您可能會想換行上述交易,以確保你不刪除不需要的記錄 - 或將陳述變爲選擇:

select st.* 
from secondTable st 
inner join firstTable ft on st.sales_id = ft.sales_id 
    and st.product_id = ft.product_id 
    and st.CreatedDate = '2015-07-04' 
3

這是因爲它純粹檢查第二張表和產品ID中是否存在銷售ID,而不是相同的記錄。

嘗試例如

Delete T2 
FROM firsttable AS T1 
INNER JOIN secondtable T2 
on T1.sales_id = T2.sales_id 
AND T1.product_id = T2.product_id 
WHERE T1.CreatedDate = '20150407' -- assuming you mean 7th April? 
+0

是4月7日謝謝 – Richard

1
DELETE 
    FROM SecondTable t2 
    JOIN FirstTable t1 
    ON t1.sales_ID = t2.sales_ID 
    AND t1.product_ID = t2.product_ID 
    AND t1.CreatedDate = '2015-07-04'