'How to display the results of two queries side by side?
In mysql, I need to display the results of these two queries, side by side, not vertically (when using UNION).
First query:
SELECT
SUM(cod = 'teste') as Cod1, id_user
FROM
Log
WHERE month = 4 AND year = 2014 AND cod = 'test'
GROUP BY
id_user
Second query:
SELECT
COUNT(*) - COUNT(DISTINCT info) as Cod2, id_user
FROM
Log
WHERE month = 4 AND year = 2014 AND cod = 'test'
GROUP BY
id_user
The result, should be something like:
Cod1 id_user Cod2 id_user
10 1 8 1
5 2 3 2
Is that possible?
Solution 1:[1]
You shouldn't need two columns for id_user because they are always going to be the same, right?
You can use subqueries to join your two queries together "side by side", like this:
SELECT
q1.id_user as id_user
q1.Cod1 as Cod1,
q2.Cod2 as Cod2
FROM
(SELECT
SUM(cod = 'teste') as Cod1,
id_user
FROM Log
WHERE month = 4 AND year = 2014
AND cod = 'test'
GROUP BY id_user) as q1
LEFT JOIN
(SELECT
COUNT(*) - COUNT(DISTINCT info) as Cod2,
id_user
FROM Log
WHERE month = 4 AND year = 2014
AND cod = 'test'
GROUP BY id_user) as q2
ON q1.id_user = q2.id_user
Or in this example, you can do it without using subqueries, like this:
SELECT
id_user,
SUM(cod = 'teste') as Cod1,
COUNT(*) - COUNT(DISTINCT info) as Cod2
FROM Log
WHERE month = 4 AND year = 2014
AND cod = 'test'
GROUP BY id_user
Code not tested, so there might be a mistake.
Solution 2:[2]
What is wrong with returning multiple columns, like normal?
SELECT
SUM(cod = 'teste') as Cod1,
COUNT(*) - COUNT(DISTINCT info) as Cod2,
id_user
FROM
Log
WHERE month = 4 AND year = 2014 AND cod = 'test'
GROUP BY
id_user
Solution 3:[3]
If you are using Oracle, you can use the following -
with
query1 as ( select .... ), -- your existing query1
query2 as ( select .... ) -- your existing query2
select *
from query1, query2
where query1.product = query2.product;
Ref - https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:9526403800346400896
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mickeybob |
Solution 2 | Lightness Races in Orbit |
Solution 3 | Leena |