嗨,我有这种情况,我很震惊。
我有两个表A和表B,它们有一个主键(panelist_id),每个panelist_id有很多entity_ids。
我想检查表中是否存在每个panelist_id和相同的entity_ids。
注意:有很多panelist_id,每个panelist_ids都有很多entity_ids ..
请帮帮我。
答案 0 :(得分:2)
要选择仅在其中一个表中可用的panelist_id / entity_id元组,请尝试执行以下操作:
select panelist_id, entity_id from
(
select panelist_id, entity_id from a
union all
select panelist_id, entity_id from b
)
group by panelist_id, entity_id
having count(*) = 1;
答案 1 :(得分:0)
Select A.panelist_id from tableA as A inner join tableB as B
on A.panelist_id=B.panelist_id
GROUP BY A.panelist_id
HAVING COUNT(DISTINCT A.entity_id)=COUNT(DISTINCT B.entity_id)
答案 2 :(得分:0)
我无法确切地知道你在问什么,如果你只是想知道每个Entity_ID / Panelist_ID元组是否存在于一个或两个表中,那么这将有效:
SELECT Panelist_ID,
Entity_ID,
CASE WHEN COUNT(A) > 0 AND COUNT(B) > 0 THEN 'Both Tables'
WHEN COUNT(B) = 0 THEN 'Table A'
WHEN COUNT(A) = 0 THEN 'Table B'
END AS Status
FROM ( SELECT Panelist_ID, Entity_ID, 1 AS A, NULL AS B
FROM A
UNION ALL
SELECT Panelist_ID, Entity_ID, NULL AS A, 1 AS B
FROM B
) T
GROUP BY Panelist_ID, Entity_ID;
如果你想知道每个表中元组相同的panelist_ID,一个表中不存在另一个不存在的元组,你需要使用它:
SELECT *
FROM A
FULL JOIN B
ON A.Panelist_ID = B.Panelist_ID
AND A.Entity_ID = B.Entity_ID
WHERE A.Entity_ID IS NOT NULL
AND B.Entity_ID IS NOT NULL;
或者如果你想知道一个表中存在的元组而不是另一个表中你可以使用的元组:
SELECT *
FROM A
FULL JOIN B
ON A.Panelist_ID = B.Panelist_ID
AND A.Entity_ID = B.Entity_ID
WHERE A.Entity_ID IS NULL
OR B.Entity_ID IS NULL;
编辑
根据关于仅需要验证临时表与永久表相同的注释,您可以使用EXISTS
:
SELECT *
FROM PermanentTable p
WHERE NOT EXISTS
( SELECT 1
FROM TempTable t
WHERE p.Panelist_ID = t.Panelist_ID
AND p.Entity_ID = t.Entity_ID
... More conditions to help find if entries are missing from temp table
)