![](/img/trans.png)
[英]Oracle SELECT QUERY for one to many relationship between two tables
[英]Query to find one to many relationship between two tables and two columns (exclude anything one to one)
該論壇新手,SQL新手。 我正在嘗試清理一些數據並找出錯誤。 我有兩個表,它們都共享FILENAME,TYPE,SEC列,我想從這兩個表中提取所有記錄,其中SEC和TYPE之間存在一對多的關系,任何包含SEC和TYPE的記錄都只有一個一種關系可以忽略,並且被認為是有效的。
例如,我在表1中。
FILENAME TYPE SEC
a----------------x----1
b----------------x----2
c----------------y----1
d----------------y----3
在表2中,我會有類似的內容,
FILENAME TYPE SEC
e----------------x----1
f----------------x----2
g----------------z----1
h----------------y----3
所以我想查詢將發現
FILENAME TYPE SEC
a----------------x----1
c----------------y----1
e----------------x----1
g----------------z----1
我的數據庫很大,任何幫助將不勝感激!
謝謝。
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
編輯:這不是您所要的,它將顯示哪些記錄具有多個記錄,但它們將被分組。
您需要查找具有多個type
的sec
值。 以下查詢可以做到這一點,並且它可以在任何數據庫上運行:
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
取決於數據庫,可能會有更有效的查詢方法。
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
第二個只是復制第一個,使用UNION ALL合並
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.