如何并排显示两个查询的结果?

时间:2014-04-24 16:53:35

标签: mysql

在mysql中,我需要并排显示这两个查询的结果,而不是垂直显示(使用UNION时)。

首先查询:

SELECT
  SUM(cod = 'teste') as Cod1, id_user
FROM
  Log
WHERE month = 4 AND year = 2014 AND cod = 'test'
GROUP BY
  id_user

第二次查询:

SELECT
  COUNT(*) - COUNT(DISTINCT info) as Cod2, id_user
FROM
  Log
WHERE month = 4 AND year = 2014 AND cod = 'test'
GROUP BY
  id_user

结果应该是:

Cod1          id_user          Cod2              id_user
 10              1              8                  1
 5               2              3                  2

这可能吗?

2 个答案:

答案 0 :(得分:1)

返回多个列有什么问题,比如正常?

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

答案 1 :(得分:0)

你不应该为id_user提供两列,因为它们总是一样的,对吗?

您可以使用子查询将两个查询一起加入"并排#34;,如下所示:

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

或者在此示例中,您可以在不使用子查询的情况下执行此操作,如下所示:

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

代码未经过测试,因此可能存在错误。