我有两张桌子:
FirstTable
包含这些列
sales_ID varchar(250)
product_ID int
SecondTable
包含这些列
sales_ID varchar(250)
product_ID int
CreateDate datetime
如果FirstTable
的{{1}}和sales_ID
与product_ID
的{{1}}和SecondTable
以及sales_Id
匹配} product_ID
是07.04.2015,我需要删除SecondTable
我试过这样:
CreatedDate
然而,它会删除所有行,并且根据我的需要,它也不正确(不工作)查询。
如果product_ID等于product_ID且sales_ID等于sales_ID且CreatedDate等于SecondTable
的07.04.2015,我如何删除重复的行?
希望你能理解我的坏英语
感谢。
答案 0 :(得分: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?
答案 1 :(得分: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'
答案 2 :(得分: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'