2017-06-05 61 views
0

ATLEAST兩種不同的結果,我有以下ER模型PostgreSQL的查詢到有相同refrence

enter image description here

我需要寫一個PostgreSQL查詢做到這一點。

選擇所有捐助者那裏:

1)Diagnosis.name starts with "abc". 

2)There should be a second Diagnosis.name for the same donor, and it should be "xyz" 

認爲這是樣本數據:

捐贈表有:

id| name    

1 |John 
2 |Sam 

事件表有:

id | event_type | donor_fk 

1 | diagnosis | 1 
2 | diagnosis | 2 
3 | diagnosis | 2 
4 | observation | 3 
5 | intervention| 3 

診斷表有:

id | name | event_FK 

1 |abc | 2 
2 |xyz | 3 

我想知道如何檢查diagn.name的兩個實例是否爲同一個捐助者?

查詢的結果應該返回名爲「Sam」的捐助者的所有數據。

因爲我發佈了這個問題,所以我沒有接近解決方案。我正在考慮診斷表自我加入的方向,但是本表中沒有提及自身,所以自我加入沒有意義。

+1

你真的應該嘗試自己的查詢,包括質疑,認爲查詢。 –

+0

@GordonLinoff我編輯了這個問題,以表明我在想什麼方向。可能你可以提供一個提示,指出從哪裏走? – rehas

+0

p.s. RDBM是'關係數據庫管理系統'。我想你想說:'我有下面的模式或實體關係圖'閱讀很多,玩得開心,回答如下;)乾杯 – PawelSz

回答

0

/*不是很有效,但有點可讀的解決辦法是:*/


select distinct a.* 
from (
    select do.id, do.name 
    from diagnosis diag 
    join event e on diag.event_fk = e.id 
     and upper(diag.name) like 'ABC%' /* here ya filter 1 */ 
    join donor do on d.id = e.donor_fk 
) a 
join (
    select do.id, do.name 
    from diagnosis diag 
    join event e on diag.event_fk = e.id 
     and upper(diag.name) like 'XYZ' /* here ya filter 2 */ 
    join donor do on d.id = e.donor_fk 
) b on a.id = b.id 
    ;