如何检查数据库中是否存在动名词关系并且有效

How to check if a gerund relationship is exist and valid in database

我有一个场景,其中我有一个 table 是多对多关系的组合,我想确保关联关系只存在一次,其中不存在重复记录.

我在这里粘贴数据,我需要确保没有重复,这违反了"gerund" 属性.

ItemID  ProductID   ProductAssociationGroupID   
3064    10084   11  
3065    10705   11  
3066    11766   68  
3067    11766   75  
3068    11772   106 
3069    11778   11  
3070    11779   98  
3071    11779   93  
3072    11793   93  
3073    12073   20  
3074    12178   12  
3075    12561   12  
3076    12561   17  
3077    12561   82  
3078    12561   81  
3079    12561   77  
3080    12561   76  
3081    12573   37  

如何查询以上数据中确切的关系只存在一次?

我一般使用的方法是用SQL GROUP BY 你要保证的列是唯一的,然后指定查询应该只return results HAVING a COUNT(* ) > 1 查找任何有多个值的地方。

例如

SELECT
    ProductID
    , ProductAssociationGroupID
    , COUNT(*) AS CountRows
FROM
    YourTable
GROUP BY 
    ProductID
    , ProductAssociationGroupID
HAVING
    COUNT(*) > 1

这应该只有 return 行有重复。

我仍在等待有关列的一些说明,但我相信使用 HAVING 子句会给您想要的结果。

Select ProductID, ProductAssociationGroupID
from [Database]
Group by ProductAssociationGroupID, ProductID
Having (Count(ProductAssociationGroupID) = 1)

如果你想查找重复项,那么我将 HAVING 子句更改为大于。