I have four tables:
Table A:
ID | B_ID
----------
1 | 5
2 | 6
3 | 7
4 | 8
Table B:
B_ID
-----
5
6
7
8
Table C:
C_ID | C_Name
--------------
5 | Alpha
6 | Beta
Table D:
D_ID | D_Name
--------------
7 | Delta
8 | Gamma
Note, that the values in Table B can come from either Table C or Table D.
I now need a query which shows ID
from Table A and a second column called Name
which consists of the corresponding names based on the B_ID
column of Table B.
The expected result should look like:
ID | Name
----------
1 | Alpha
2 | Beta
3 | Delta
4 | Gamma
What I tried is this query:
SELECT *
FROM B
LEFT OUTER JOIN C
ON B_ID = C_ID
LEFT OUTER JOIN D
ON B_ID = D_ID
This yields:
B_ID | C_ID | C_Name | D_ID | D_Name
-------------------------------------
5 | 5 | Alpha | Null | Null
6 | 6 | Beta | Null | Null
7 | Null | Null | Null | Delta
8 | Null | Null | Null | Gamma
However, I still have two issues:
SELECT
based on
Table A in order to show the ID
column of Table A.SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function. This method will change the original table.
select column1 || ' ' || column2 as whole_name FROM tablename; Here || is the concat operator used for concatenating them to single column and ( '' ) inside || used for space between two columns. Save this answer.
Select the same number of columns for each query. Corresponding columns must be the same general data type. Corresponding columns must all either allow null values or not allow null values. If you want to order the columns, specify a column number because the names of the columns you are merging are probably different.
Here's one option using a subquery with union all
:
select a.id, b.name
from tablea a
join (select id, name from tablec
union all select id, name from tabled) b on a.B_ID = b.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With