Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two sql queries into one

Tags:

sql

How can I combine these two SQL statements?

SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09) AS 'AEROwiz'
FROM tbl_2011
WHERE appName='AEROwiz'

SELECT SUM(hits10 + hits11 + hits12) AS 'AEROwiz'
FROM tbl_2010
WHERE appName='AEROwiz'

hits10, hits11 and hits12 exist in both tables.

like image 589
Anthony Avatar asked Nov 01 '11 19:11

Anthony


People also ask

How do I merge 3 queries in SQL?

If you want two more rows, then use UNION ALL. You still kind of have 3 queries but executed as one. If you want two more columns, then use SUM(CASE(...)). Basically you more your WHERE clause to the CASE clause 3 times each with own condition.

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.


1 Answers

Use a UNION query - just stuff "UNION" between the two queries:

SELECT SUM(...) AS AEROWiz
FROM ...

UNION

SELECT SUM(...) AS AEROWiz
FROM ...

update

wrap the union in yet another query:

SELECT SUM(AEROWiz)
FROM (
    .... unioned queries here
) AS child
like image 149
Marc B Avatar answered Sep 28 '22 11:09

Marc B