TSQL - 从表A中检索包含表B中包含的确切数据的结果

时间:2014-03-13 17:31:01

标签: sql sql-server tsql

我有TableA(id bigint,名称varchar)和TableB(名称varchar),其中包含以下数据:

Table A:                        Table B:                      Results:
-------------                  ---------                   ---------------
|  1 | "A"  |                  |  "A"  |                   |  1  |  "A"  |
|  1 | "B"  |                  |  "B"  |                   |  1  |  "B"  |
|  2 | "A"  |                  ---------                   |  4  |  "A"  |
|  3 | "B"  |                                              |  4  |  "B"  |
|  4 | "A"  |                                              ---------------
|  4 | "B"  |
-------------

我想从TableA返回结果,其中包含表B中的内容的精确匹配。 使用' IN'子句只检索一个事件。

另外,另一个例子,如果TableB只有" A",我希望它返回:2 - " A"

2 个答案:

答案 0 :(得分:0)

这适用于SQL Server

select * from TableA a
where
 (select count(*) from TableB) = (select count(*) from TableA where id = a.id) and
 (select count(*) from TableB) = 
 (
  select count(*) from
  (
   select name from TableA where id = a.id
   intersect
   select name from TableB
  ) as b
 )

答案 1 :(得分:0)

我理解你的问题,但这是一个棘手的问题,因为它与关系逻辑并不完全一致。您正在查找SELECT name FROM TableA WHERE id IN ... ORDER BY name;SELECT name FROM B order by name;相同的ID。

您能否认为A(id,name)是唯一的且B(name)是唯一的?更好的说,有这样的限制,还是你可以设置它们?

如果是,这是一个解决方案:

1。摆脱A中的ID,其行与B

中的行不匹配
SELECT id, A.name FROM A WHERE id NOT IN
    (SELECT id FROM A LEFT JOIN B ON A.name = B.name WHERE B.name IS NULL);

2。计算每个id的行数(这就是必要的唯一约束)

SELECT id, COUNT(*) FROM
    (
        SELECT id, A.name FROM A WHERE id NOT IN
        (SELECT id FROM A LEFT JOIN B ON A.name = B.name WHERE B.name IS NULL)
    ) t
GROUP BY id;

3。仅保留与B

的行数匹配的项目
SELECT id, COUNT(*) FROM
    (
        SELECT id, A.name FROM A WHERE id NOT IN
        (SELECT id FROM A LEFT JOIN B ON A.name = B.name WHERE B.name IS NULL)
    ) t
GROUP BY id
HAVING COUNT(*) = SELECT COUNT(*) FROM B;