Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fetch attributes from a source table depending on which table the id lookup is in?

I need help with this SQL query: https://www.db-fiddle.com/f/wwJa42bepizQAsgLVbzETD/0

With some base and source tables:

CREATE TABLE SOURCE2 (
    id VARCHAR(255),
    source_name VARCHAR(255)
);

CREATE TABLE SOURCE1 (
    id VARCHAR(255),
    source_name VARCHAR(255)
);

CREATE TABLE BASE (
   id VARCHAR(255),
   source_name VARCHAR(255)
);

INSERT INTO BASE (id, source_name) VALUES 
    (1,'base'),
    (2,'base'),
    (3,'base'),
    (4,'base'),
    (5,'base'),
    (6,'base');
    
INSERT INTO SOURCE2 (id, source_name) VALUES 
    (2, 'source1'),
    (4, 'source1'),
    (6, 'source1');

INSERT INTO SOURCE1 (id, source_name) VALUES 
    (1, 'source1'),
    (3, 'source1'),
    (5, 'source1');

I want to be able to join attributes selectively from source1 and source2 based on the id that the source table matches in the base table. So if the id is in source1 then use ‘source1’ as the name and if the id is in source2 use ‘source2’ as the name. Because of the order of ids that I chose I expect the results to look like;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

source1
source2
source1
source2
source1
source2

Here is my query that Im attempting

SELECT COALESCE(SOURCE1.source_name, SOURCE2.source_name) as source_name
FROM BASE
LEFT JOIN SOURCE1 ON SOURCE1.id = BASE.id
LEFT JOIN SOURCE2 ON SOURCE2.id = BASE.id

Right now the results look like this:

source1
source1
source1
source1
source1
source1

Why is SOURCE1.source_name not null when base.id is 2 for instance?

>Solution :

You are inserting ‘source1’ text in source2 table

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading