如何检查仅与一个值绑定到其相关表的id

时间:2017-01-27 03:54:51

标签: sql sql-server tsql

我有两个表,我需要检查UCCID是否仅作为测试的一部分与一个BUYID绑定。 UCCID应该是我桌子的独特之处。但是BUyid可以拥有多个UCCID。但UCCID应该与独特(仅一个)BUYID联系在一起。

CREATE TABLE [dbo].[EquipmentBase](
           [EDAEquipmentId] [uniqueidentifier] NOT NULL,
           [BuyID] [nvarchar](100) NULL,
           [EqtAE] [nvarchar](100) NULL,
           [EqtSn] [nvarchar](100) NULL,
           [EqtSz] [nvarchar](100) NULL,
           [EqtUccYr] [nvarchar](100) NULL,
           [EqtUnit] [nvarchar](100) NULL,
           [EqtValue] [nvarchar](100) NULL,
           [UccID] [NVARCHAR](100) NULL,
           CONSTRAINT [PK__EquipmentBase] PRIMARY KEY CLUSTERED
    (
           [_EDAEquipmentId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
    ) ON [PRIMARY]

    GO


    CREATE TABLE [dbo].[activityBase](
           [activityId] [UNIQUEIDENTIFIER] NOT NULL,
           [UccID] [NVARCHAR](100) NULL,
           [ASCity] [NVARCHAR](100) NULL,
           [ASClass] [NVARCHAR](100) NULL,
           [ASComp] [NVARCHAR](100) NULL,
           [ASID] [NVARCHAR](100) NULL,
           [ASState] [NVARCHAR](100) NULL,
           [BuyADR1] [NVARCHAR](100) NULL,
           [BuyADR2] [NVARCHAR](100) NULL,
           [BuyID] [NVARCHAR](100) NULL,
           [UccCom] [NVARCHAR](100) NULL,
           [UccDate] [DATETIME] NULL,
           [UccFips2] [NVARCHAR](100) NULL,
           [UccStatus] [NVARCHAR](100) NULL,
           [UccTransID] [NVARCHAR](100) NULL,
           CONSTRAINT [PK__activityBase] PRIMARY KEY CLUSTERED
    (
           [activityId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

我尝试了以下查询但是我没有得到我正在研究的结果?任何人都可以帮忙吗?我希望下面的查询返回0,以便UCCID与单个BUYID绑定。

  SELECT COUNT(*) FROM dbo.activityBase ab
        JOIN (SELECT eb.BuyID FROM dbo.EquipmentBase eb
        WHERE eb.UccID IS NOT NULL
        GROUP BY eb.BuyID
        HAVING COUNT(eb.BuyID)=1)c
        ON c.BuyID = ab.BuyID

1 个答案:

答案 0 :(得分:1)

如果我理解正确(并且您的问题不是非常明确),如果您要确定UccID的任何值,哪些记录存在多个BuyID的不同值(跨越SELECT UccId, COUNT(*) FROM ( SELECT DISTINCT BuyID, UccID FROM EquipmentBase UNION SELECT DISTINCT BuyID, UccID FROM activityBase ) AS DistinctCombos GROUP BY UccId HAVING COUNT(*) > 1 你的两个表),你可以使用:

FROM

这使用UccID子句中的子查询返回两个表中两个字段的所有组合,然后检查这些结果以查找具有多个不同BuyID的任何applicationId值对他们的价值。