[英]Query to find one to many relationship between two tables and two columns (exclude anything one to one)
New to this forum, and new to SQL. 该论坛新手,SQL新手。 I'm trying to clean up some data and pull out the errors.
我正在尝试清理一些数据并找出错误。 I have two tables, which both share the columns FILENAME, TYPE, SEC, I would like to pull out any records from both tables where there is a one to many relationship between SEC and TYPE, anything with a SEC and TYPE where only a one to one relationship can be ignored and is considered valid.
我有两个表,它们都共享FILENAME,TYPE,SEC列,我想从这两个表中提取所有记录,其中SEC和TYPE之间存在一对多的关系,任何包含SEC和TYPE的记录都只有一个一种关系可以忽略,并且被认为是有效的。
For Example, I have in table1. 例如,我在表1中。
FILENAME TYPE SEC
a----------------x----1
b----------------x----2
c----------------y----1
d----------------y----3
in table2 i would have something similar, 在表2中,我会有类似的内容,
FILENAME TYPE SEC
e----------------x----1
f----------------x----2
g----------------z----1
h----------------y----3
so i would like a query that would find 所以我想查询将发现
FILENAME TYPE SEC
a----------------x----1
c----------------y----1
e----------------x----1
g----------------z----1
My database is very large and any help would be much appreciated! 我的数据库很大,任何帮助将不胜感激!
Thanks. 谢谢。
select t1.sec, t1.type, count(*) from table1 as t1
join table2 as t2 on t1.sec = t2.sec and t1.type = t2.type
group by t1.sec, t1.type
having count(*) > 1
EDIT: That's not quite what you asked, that will show which ones have multiple records but they will be grouped. 编辑:这不是您所要的,它将显示哪些记录具有多个记录,但它们将被分组。
You need to find the values of sec
that have more than one type
. 您需要查找具有多个
type
的sec
值。 The following query does this and it should work on any database: 以下查询可以做到这一点,并且它可以在任何数据库上运行:
select t.*
from ((select t1.*
from t1
) union all
(select t2.*
from t2
)
) t join
(select sec
from ((select t1.*
from t1
) union all
(select t2.*
from t2
)
) t
group by sec
having count(distinct type) > 1
) s
on t.sec = s.sec
There may be more efficient ways of doing the query, depending on the database. 取决于数据库,可能会有更有效的查询方法。
select 'table1' which, t.*
from (
select sec, min(type) typea, max(type) typeb
from table1
group by sec
having min(type) <> max(type)
) x
join table1 t on t.sec = x.sec
UNION ALL
select 'table2', t.*
from (
select sec, min(type) typea, max(type) typeb
from table1
group by sec
having min(type) <> max(type)
) x
join table2 t on t.sec = x.sec
The 2nd one just duplicates the first, combined using UNION ALL 第二个只是复制第一个,使用UNION ALL合并
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.