Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining 2 SQL SELECT result sets into one

I've got 2 select statements, returning data like this:

Select 1
col_a   col_b

Select 2
col_a   col_c

If I do union, I get something like

col_a col_b

And rows joined. What i need is getting it like this:

col_a  col_b  col_c

Joined on data in col_a

like image 231
Vance Avatar asked Feb 23 '10 11:02

Vance


People also ask

How can you combine and return the result set retrieved by two or more SELECT?

The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It does not remove duplicate rows between the various SELECT statements (all rows are returned). Each SELECT statement within the UNION ALL must have the same number of fields in the result sets with similar data types.

How do I combine two SQL queries in one result without a UNION?

You need to create two separate queries and join their result not JOIN their tables. Show activity on this post. JOIN and UNION are differents. In your query you have used a CROSS JOIN operation, because when you use a comma between two table you apply a CROSS JOIN.

How do you do a join with SELECT in SQL?

Different Types of SQL JOINs(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.


3 Answers

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

like image 63
Mark Byers Avatar answered Oct 19 '22 23:10

Mark Byers


Use a FULL OUTER JOIN:

select 
   a.col_a,
   a.col_b,
   b.col_c
from
   (select col_a,col_bfrom tab1) a
join 
   (select col_a,col_cfrom tab2) b 
on a.col_a= b.col_a
like image 4
p2u Avatar answered Oct 19 '22 23:10

p2u


SELECT table1.col_a, table1.col_b, table2.col_c 
  FROM table1 
  INNER JOIN table2 ON table1.col_a = table2.col_a
like image 2
Håvard S Avatar answered Oct 19 '22 21:10

Håvard S