[英]sql verify relationship over two tables
I have two tables: A and B 我有两个表:A和B
Table A columns: 表A列:
content_key data_key content_key data_key
Table B columns: content_key person_key 表B列:content_key person_key
I need to verify that for each data_key there is only one person_key that is associated with it, it can have the same person_key multiple times but only one unique value. 我需要验证,对于每个data_key,只有一个与之关联的person_key,它可以多次具有相同的person_key,但只有一个唯一值。
You should be able to use COUNT()
and GROUP BY
the data_key
and person_key
您应该能够使用
COUNT()
和GROUP BY
data_key
和person_key
SELECT count(data_key) cnt, data_key, person_key
FROM tableA a
INNER JOIN tableB b
ON a.content_key = b.content_key
GROUP BY data_key, person_key
A good way to do this is with COUNT(DISTINCT): 一个好的方法是使用COUNT(DISTINCT):
select A.data_key, count(distinct person_key) as numPersons
from A join
B
on A.content_key = B.content_key
group by A.data_key
order by 2 desc
I added the order by, so you can see the duplicates first. 我添加了订单,因此您可以先看到重复的订单。
Well, since you want to verify rather than see the duplicates, add a HAVING clause: 好吧,由于您要验证而不是查看重复项,因此添加一个HAVING子句:
having count(distinct person_key) > 1
If the query returns no rows, then the data meets your condition. 如果查询不返回任何行,则数据符合您的条件。
Also, this assumes that person_key is never NULL. 此外,这还假设person_key永远不会为NULL。 The count is a bit more complicated if that can happen:
如果发生这种情况,则计数会稍微复杂一些:
(COUNT(distinct person_key) + max(case when person_key is null then 1 else 0 end))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.