我有以下表,我需要删除满足给定条件的行。
请帮助我。
表: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 productname
和datecreated
的行,以及productcategory
表中未包含的行
即,我想删除
ProductId 2 and ProductId 3
因为它具有相同的 ProductName
具有相同的 DateCreated
,并且在 ProductCategory
表中也不包含
预先感谢
您首先可以这样做以删除所有未在ProductCategory表中的产品:
步骤1
Delete from Product
Where productId not IN(select productId from ProductCategory)
然后,如果您仍然想从产品表中删除重复项,则可以尝试以下操作:
步骤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
表中包含所有相应的行
步骤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
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小提琴演示