嗨,我有这种情况,我很震惊。
我有两个表,表 A 和表 B,它们有一个共同的主键(panelist_id),并且对于每个 panelist_id,都有许多 entity_id。
我想检查表中是否存在每个 panelist_id 和相同的 entity_ids。
注意:有很多 panelist_id,每个 panelist_id 都有很多 entity_id。
请帮帮我。
要选择仅在其中一个表中可用的 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;
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)
我不能确切地知道你在问什么,如果你只想知道每个 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
)