Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining output of two or more select statement

How to combine output of two or more SELECT statements, I have multiple tables which are having some data that I need to fetch them so I write multiple SELECT query. Now I want to combine result of the queries so what do I need to do ? I want the output to be:

t1.qty,t2.qty,t3.qty 
like image 228
user2485642 Avatar asked Aug 13 '13 07:08

user2485642


People also ask

How do I combine two columns of output in SQL?

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 merge two MySQL queries?

The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.


2 Answers

One option would be:

SELECT (SELECT SUM(qty) FROM Table1 WHERE ...),
       (SELECT SUM(qty) FROM Table2 WHERE ...),
       (SELECT SUM(qty) FROM Table3 WHERE ...)

Another would be joining, provided that there is a link:

SELECT * 
FROM   (SELECT ID,SUM(qty) FROM Table1 GROUP BY ID) T1
       JOIN (SELECT ID,SUM(qty) FROM Table2 GROUP BY ID) T2
           ON T1.ID = T2.ID
       JOIN (SELECT ID,SUM(qty) FROM Table3 GROUP BY ID) T3
           ON T1.ID = T3.ID

The above options would be to display results in one row.

You may need union to combine rows:

SELECT qty FROM Table1
UNION
SELECT qty FROM Table2
UNION
SELECT qty FROM Table3

Much more options if you define more specific needs

like image 133
Giannis Paraskevopoulos Avatar answered Sep 22 '22 03:09

Giannis Paraskevopoulos


Why not create a statement that will fetch them all at once?

SELECT tableA.data1, tableB.data2 FROM tableA, tableB WHERE <condition here>
like image 45
bry Avatar answered Sep 23 '22 03:09

bry