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;
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