获取单个查询中两个SQL表中的列数?

时间:2011-04-19 16:23:28

标签: sql

我写了两个SQL语句:

SELECT Count(*) AS table1Count FROM table1 WHERE foo=1;
SELECT Count(*) AS table2Count FROM table2 WHERE bar=2;

两个语句都返回我想要的数据,但我想知道如何返回一个包含两个单元格的表:table1Count和table2Count来自单个查询。

如何构建查询?

2 个答案:

答案 0 :(得分:5)

SELECT (SELECT Count(*) AS table1Count FROM table1 WHERE foo=1) AS table1Count, 
       (SELECT Count(*) AS  table2Count FROM table2 WHERE bar=2) AS table2Count;

给出类似的东西:

 table1count | table2count 
-------------+-------------
           4 |           6
(1 row)

答案 1 :(得分:3)

使用UNION ALL

SELECT 'Table1' AS "Table", Count(*) As "Count" FROM table1 WHERE foo=1
UNION ALL
SELECT 'Table2' AS "Table", Count(*) As "Count" FROM table2 WHERE bar=2;

将产生:

Table  | Count
---------------
Table1 | 1
Table2 | 2