Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql left join multiple conditions

I am still a NB to PostgreSQL - can anyone help with this query:

select distinct j.id, tt.title, m_scopus.provider_id
from journal j   
join temporal_title "tt"   
     on (j.id = tt.journal_id and tt.list_index = 0) 
left join journal_metrics "jm_scopus"  
     on (jm_scopus.journal_id = j.id) 
left join metrics "m_scopus" 
     on (m_scopus.id = jm_scopus.metrics_id 
     and m_scopus.source_id = 235451508 
     and m_scopus.year_integer = 2017)

The problem is that I get rows with empty "provider_id" where I don't want them:

journal_id     title                    provider_id
263290036      German Journal of...     scopusJournalsMetricsProvider
263290036      German Journal of...     NULL
72418282       Europa azul              NULL    
207412571      IAC International...     NULL

Rows 1, 3 and 4 are OK, but row 2 is not OK, because I the information I need is provider_id if it is there and just NULL if it is not.

like image 864
pmelch Avatar asked Oct 15 '25 22:10

pmelch


1 Answers

If I understand your data(model) correctly, the journal_metrics table is a junction table, which is not needed in the final result, so it can be kept out of the main query, avoiding the double LEFT JOIN:


SELECT j.id, tt.title, m.provider_id
FROM journal j
JOIN temporal_title tt  
    ON j.id = tt.journal_id AND tt.list_index = 0
LEFT JOIN metrics m 
        ON m.source_id = 235451508
        AND m_scopus.year_integer = 2017
        AND EXISTS ( SELECT *
                FROM journal_metrics jm -- The junction table
                WHERE jm.journal_id = j.id 
                AND jm.metrics_id = m.id 
                )
        ;
like image 60
wildplasser Avatar answered Oct 18 '25 15:10

wildplasser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!