1

我有一张像下面这样的桌子

CREATE TABLE [dbo].[MyTable](
    [MyTableID]    [int]           IDENTITY(1,1) NOT NULL,
    [ContainerID]  [int]           NOT NULL,
    [FIELD_A]      [nvarchar](15)  NOT NULL,
    [FIELD_B]      [nvarchar](15)  NOT NULL,
    [FIELD_C]      [nvarchar](15)  NOT NULL,
    [FIELD_D]      [nvarchar](50)  NULL,
 CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableID] 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]

简单来说,FIELD_AFIELD_B由分组。FIELD_CFIELD_DContainerID

考虑到每个容器包含大约 2k 条记录,我想执行一个返回两个ContainerID. 例如,在比较容器 1 和容器 2 时,我需要知道:

  • 1 中存在多少条记录,2 中没有,反之亦然
  • 两个容器中存在多少条记录

获得这些结果的最简单方法是什么?谢谢!

4

2 回答 2

2

这是一个开始:

-- rows for 1 but not in 2:

SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D FROM dbo.MyTable WHERE ContainerID = 1
EXCEPT
SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D FROM dbo.MyTable WHERE ContainerID = 2;

-- rows for 2 but not in 1:

SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D FROM dbo.MyTable WHERE ContainerID = 2
EXCEPT
SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D FROM dbo.MyTable WHERE ContainerID = 1;

-- rows in both:

SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D FROM dbo.MyTable WHERE ContainerID = 1
INTERSECT
SELECT FIELD_A, FIELD_B, FIELD_C, FIELD_D FROM dbo.MyTable WHERE ContainerID = 2;
于 2012-09-12T14:42:32.787 回答
1

这应该可行,您必须索引所有四个“field_x”字段,但它仍然不会很快

SELECT isnull(t1.Field_A,t2.Field_A) Field_A, isnull(t1.Field_B,t2.Field_B) Field_B
, isnull(t1.Field_C,t2.Field_C) Field_C, isnull(t1.Field_D,t2.Field_D) Field_D
,CASE WHEN t1.MyTableId IS NULL THEN 1 ELSE 0 END
,CASE WHEN t2.MyTableId IS NULL THEN 1 ELSE 0 END
FROM
(SELECT * FROM MyTable WHERE ContainerId=@ContainerId1) t1
FULL OUTER JOIN 
(SELECT * FROM MyTable WHERE ContainerId=@ContainerId2) t2
ON t1.Field_A=t2.Field_A AND t1.Field_B=t2.Field_B 
AND t1.Field_C=t2.Field_C AND t1.Field_D=t2.Field_D
于 2012-09-12T14:46:33.350 回答