0

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

请帮我。

桌子: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 productnameand的行以及表 datecreated中不包含的行productcategory

即,我想删除

  ProductId 2 and ProductId 3

因为它具有相同ProductName的相同DateCreated并且也不包含在ProductCategory表中

提前致谢

4

2 回答 2

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)

然后继续第 4 步

于 2012-10-19T12:36:03.643 回答
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

于 2012-10-19T12:16:29.450 回答