Join with keys of both tables

All we need is an easy explanation of the problem, so here it is.

I try to bring to tables together in a join-like way. Consider the column id_ as "on clause" key. In the tables below, there are more id_s in table 1 than 2. I would like to have all ids and values of both tables. If there is not a respective id_, the value is 0 or null.

CREATE TABLE IF NOT EXISTS t1 (
   id_ INTEGER  NOT NULL,
   value1 INT NOT NULL
)

CREATE TABLE IF NOT EXISTS t2 (
   id_ INTEGER  NOT NULL,
   value2 INT NOT NULL
)

INSERT INTO t1 (id_, value1) VALUES
(1, 10),
(2, 20),
(3, 30)

INSERT INTO t2 (id_, value2) VALUES
(2, 40),
(3, 60)
(4, 80)

I use the platform Metabase, a BI tool.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In MySQL (which does not support FULL JOIN) you must use gathering subquery:

SELECT id_, t1.value1, t2.value2
FROM ( SELECT id_ FROM t1
       UNION 
       SELECT id_ FROM t2 ) total
LEFT JOIN t1 USING (id_)
LEFT JOIN t2 USING (id_);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply