两个表分为两个单独的列

时间:2015-01-02 06:22:50

标签: mysql sql select count subquery

我有两张桌子,例如:

table1
---------------------
|id | name| isActive|
|---|-----|---------|
| 1 | dd  |    1    |
| 1 | cc  |    1    |
| 1 | zz  |    1    |
| 1 | yy  |    1    |
---------------------


table2
---------------------
|id | name| isActive|
|---|----|----------|
| 1 | ab  |    1    |
| 1 | cd  |    1    |
| 1 | ef  |    1    |
| 1 | gh  |    1    |
---------------------

要求是获取两个表的计数并将它们打印到两个单独的列中并将其打印到birt中的两个单独的列中报告我已经尝试过这个

SELECT 
  COUNT(table2.`name`) Table1Count,
  table1.`isActive` Table1IsActive ,
  COUNT(table2.`name`) Table2Count,
  table2.`isActive` Table2IsActive 
FROM
  `table1`,
  `table2`

它的输出位于两个单独的列中,但具有交叉连接

Table1Count  isActive  Table2Count  Table2IsActive  
-----------  --------  -----------  ----------------
  43316         0         3536                 1

我不能使用任何连接,因为这两个表中没有任何关系,而它的输出类似于所需的输出,我希望在不同的列中有两个表计数

通过尝试这个我得到两个单独的行

SELECT 
  * 
FROM
   (SELECT 
   COUNT(*) Table1Count,
    table1.`isActive` Table1IsActive 
  FROM
    `table1` 
  UNION
  SELECT 
    COUNT(*) Table2Count,
    table2.`isActive` Table2IsActive 
  FROM
    `table2 `) AS a 

它的输出分为两行,而我的要求是单独的列

Table1Count   Table1IsActive 
------------   --------------
    442           0
     98           1

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT (SELECT COUNT(*) FROM `table1`) AS Table1Count, 
       (SELECT COUNT(*) FROM `table2`) AS Table2Count;

答案 1 :(得分:1)

在您的UNION中,为另一个表中的列添加额外的列。然后使用MAX()

组合它们
SELECT MAX(Table1Count) AS Table1Count, MAX(Table1IsActive) AS Table1IsActive,
       MAX(Table2Count) AS Table2Count, MAX(Table2IsActive) AS Table2IsActive
FROM (SELECT COUNT(*) Table1Count, table1.`isActive` Table1IsActive, 0 Table2Count, 0 Table2IsActive
      FROM `table1` 
      UNION
      SELECT 0 Table1Count, 0 Table1IsActive, COUNT(*) Table2Count, table2.`isActive` Table2IsActive 
      FROM `table2`) AS a 

答案 2 :(得分:1)

UNION将始终使用联合中第一个选择的列名。由于两个查询都返回一行,您可以使用的是一个简单的笛卡尔积(1 x 1 = 1)来组合查询:

SELECT t1.Table1Count, t1.Table1IsActive, t2.Table2Count, t2.Table2IsActive
FROM
   (SELECT 
   COUNT(*) Table1Count,
   table1.isActive Table1IsActive 
  FROM
    table1
  GROUP BY table1.isActive
    ) as t1,
  (SELECT 
    COUNT(*) Table2Count,
    table2.isActive Table2IsActive 
  FROM
    table2 
  GROUP BY table2.isActive      
  ) as t2;

修改

从评论中更新 - 我相信你所追求的是如下,即计算所有行并且还只计算活动行(在一个查询中),然后在两个表中重复这一行,以投影单行结果:

SELECT 
       t1.Table1Count, t1.Table1Active, t2.Table1Count, t2.Table2Active
FROM
    (
       SELECT COUNT(t1.id) AS Table1Count, 
              SUM(CASE WHEN t1.IsActive = '1' THEN 1 ELSE 0 END) AS Table1Active 
       FROM Table1 t1
    ) t1,
    (
       SELECT COUNT(t2.id) AS Table1Count, 
              SUM(CASE WHEN t2.IsActive = '1' THEN 1 ELSE 0 END) AS Table2Active 
       FROM Table2 t2
    ) t2;

重要的是,两个派生表(t1和t2)都要展平为单行,否则笛卡儿积将重复行。