Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select merge two columns into one

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:

  1. I need to merge the names into a single column (see the expected result above)
  2. It needs to be a subquery of a SELECT based on Table A in order to show the ID column of Table A.
like image 813
beta Avatar asked Jul 25 '16 14:07

beta


People also ask

How do I combine two columns in SELECT query?

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.

How do I combine two columns into a single column in SQL?

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.

How do I combine data from multiple columns into one in SQL?

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.


1 Answers

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
like image 121
sgeddes Avatar answered Sep 21 '22 00:09

sgeddes