I need to select all rows from table 1 and join data from table 2 by t1_id=t1id (with filtering by year, for example - 2020, and sorting by data, for example ASC), but if there is no corresponding row in table 2, then set some default value (for example - null). Desired result:
| t1id | title | t2id | t1_id | year | data |
|---|---|---|---|---|---|
| 4 | DDD | 103 | 4 | 2020 | 142 |
| 1 | AAA | 101 | 1 | 2020 | 574 |
| 2 | BBB | NULL | NULL | NULL | NULL |
| 3 | CCC | NULL | NULL | NULL | NULL |
When I tried to use some kind of JOIN the rows BBB and CCC are removed from the results:
create table table1 (t1id integer, title varchar(100));
insert into table1 (t1id, title) values (1, 'AAA');
insert into table1 (t1id, title) values (2, 'BBB');
insert into table1 (t1id, title) values (3, 'CCC');
insert into table1 (t1id, title) values (4, 'DDD');
create table table2 (t2id integer, t1_id integer, year integer, data integer);
insert into table2 (t2id, t1_id, year, data) values (100, 1, 2019, 333);
insert into table2 (t2id, t1_id, year, data) values (101, 1, 2020, 574);
insert into table2 (t2id, t1_id, year, data) values (102, 3, 2019, 235);
insert into table2 (t2id, t1_id, year, data) values (103, 4, 2020, 142);
SELECT * FROM table1
LEFT OUTER JOIN table2 ON table2.t1_id=table1.t1id
WHERE table2.year=2020
ORDER BY table2.data ASC
Example in sqlfiddle - http://sqlfiddle.com/#!9/ba99b1/1/0
The result of this code is:
| t1id | title | t2id | t1_id | year | data |
|---|---|---|---|---|---|
| 4 | DDD | 103 | 4 | 2020 | 142 |
| 1 | AAA | 101 | 1 | 2020 | 574 |
What should I add to the code to get desired result (with rows BBB and CCC too)?