问题
I have two tables in SQL that look similar to the following:
Code Symbol Value
1203 ABC 10.00
1208 XYZ 12.00
1222 null 9.00
1226 ABC 1.00
and
Symbol Date
ABC 2020-06-07
XYZ 2020-06-08
QRS 2020-06-10
Currently, I am trying to join them as follows
SELECT a.Code, a.Symbol, a.Value, b.Date
FROM table1 a
LEFT JOIN table2 b ON a.Symbol = b.Symbol
This returns the following output:
Code Symbol Value Date
1203 ABC 10.00 2020-06-07
1208 XYZ 12.00 2020-06-08
1226 ABC 1.00 2020-06-07
However, I would like to still keep all rows from the initial table as such and fill in the missing values as null as such:
Code Symbol Value Date
1203 ABC 10.00 2020-06-07
1208 XYZ 12.00 2020-06-08
1222 null 9.00 null
1226 ABC 1.00 2020-06-07
I know this is likely quite straightforward but I have tried researching it and I think I am having a brain cramp because I can't work my issue correctly to find what I need.
Thanks for the help.
回答1:
Edit: I agree with @Gordon Linoff, you probably have your tables in reverse order. Either flip the tables, or use a RIGHT JOIN
instead.
Sounds like you want a LEFT (OUTER) JOIN
. For a general overiew, see here.
WITH a AS (
SELECT *
FROM (VALUES (1203, 'ABC', 10.00),
(1208, 'XYZ', 12.00),
(1222, null, 9.00),
(1226, 'ABC', 1.00)
) as a (code, symbol, value)
), b AS (
SELECT *
FROM (VALUES ('ABC', '2020-06-07'::date),
('XYZ', '2020-06-08'::date),
('QRS', '2020-06-10'::date)
) as b (symbol, date)
)
SELECT code, a.symbol, value, date
FROM a LEFT JOIN b ON a.symbol = b.symbol
+----+------+-----+----------+
|code|symbol|value|date |
+----+------+-----+----------+
|1203|ABC |10 |2020-06-07|
|1208|XYZ |12 |2020-06-08|
|1222|NULL |9 |NULL |
|1226|ABC |1 |2020-06-07|
+----+------+-----+----------+
来源:https://stackoverflow.com/questions/63493602/is-there-way-to-join-two-tables-in-sql-not-on-you-index-row-without-getting-rid