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

如何在sql中使用以下条件删除记录,sql,delete-row,delete-record,Sql,Delete Row,Delete Record,我有以下表格,需要删除满足给定条件的行 请帮帮我 表:产品 表:类别 表:产品类别 现在,我想删除从第一个表中创建的count>1 group by productname和datecreated的行,以及productcategory表中不包含的行 i、 e,我想把它移走 ProductId 2 and ProductId 3 因为它具有相同的ProductName和相同的创建日期,并且不包含在ProductCategory表中 提前谢谢 delete Product from Prod

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

请帮帮我

表:产品

表:类别

表:产品类别

现在,我想删除从第一个表中创建的count>1 group by productname和datecreated的行,以及productcategory表中不包含的行

i、 e,我想把它移走

  ProductId 2 and ProductId 3
因为它具有相同的ProductName和相同的创建日期,并且不包含在ProductCategory表中

提前谢谢

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
    )

您可以首先执行此操作以删除不在ProductCategory表中的所有产品:

第一步

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
表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

您的一个表中存在错误。ProductCategory应该在categoryid列中包含1、2和3,而不是类别名称。谢谢LugiEdlCarno。我编辑了这个问题。那么答案对您有帮助吗?如果productname和datecreated是相同的,并且表中有两行,那么将考虑计数
Delete Product 
From Product, TheKeys
Where Product.productname = TheKeys.productname
and Product.datecreated = TheKeys.datecreated
Insert into Product (productId, productname, datecreated)
Select * From TheRows
Delete From TheRows
Where productId not In(Select productId from ProductCategory)