如何在sql中使用以下条件删除记录

时间:2012-10-19 12:07:51

标签: sql delete-row delete-record

我有以下表格,我需要删除满足给定条件的行。

请帮帮我。

表:Product

productId productname datecreated
1         sample1     20/01/2012
2         sample1     20/01/2012
3         sample2     20/02/2012
4         sample2     20/02/2012
5         sample2     20/09/2012
6         sample1     20/08/2012

表:Category

categoryid categoryname
1          cat1
2          cat2
3          cat3

表:ProductCategory

postid  categoryid
1         1
4         2

现在我要删除第一个表中包含count > 1 group by productnamedatecreated的行,以及productcategory表中未包含的行

即,我想删除

  ProductId 2 and ProductId 3

因为ProductName具有相同的DateCreated,并且未包含在ProductCategory表中

提前致谢

2 个答案:

答案 0 :(得分:0)

delete Product
from Product as P
where
    P.productId not in (select T.postid from ProductCategory as T) and
    exists
    (
        select T.*
        from Product as T
        where
            T.productId <> P.productId and
            T.productname = P.productname and
            T.datecreated = P.datecreated
    )

<强> sql fiddle demo

答案 1 :(得分:0)

您可以先删除所有不在ProductCategory表中的产品:

第1步

Delete from Product 
Where productId not IN(select productId from ProductCategory)

然后,如果您仍想删除Product表中的重复项,可以试试这个:

第2步

Select productname, datecreated, Count(*)
Into TheKeys
from Product 
Group by productname, datecreated
Having Count(*)>1

此TheKeys表将包含重复值

第3步

Select DISTINCT Product.*
Into TheRows
From Product, TheKeys
Where Product.productname = TheKeys.productname
And Product.datecreated = TheKeys.datecreated

表TheRows包含所有相应的行

第4步

Delete Product 
From Product, TheKeys
Where Product.productname = TheKeys.productname
and Product.datecreated = TheKeys.datecreated

这会删除所有重复的行

最后将唯一的行放回到表格中:

第5步

Insert into Product (productId, productname, datecreated)
Select * From TheRows

注意:如果您不介意拥有不属于任何类别的产品 您可以省略第一步并在第3步之后执行此操作

Delete From TheRows
Where productId not In(Select productId from ProductCategory)

然后继续使用STEP 4