在单个查询中获取两个SQL表中的列数?
问题描述:
我已经写了两个SQL语句:在单个查询中获取两个SQL表中的列数?
SELECT Count(*) AS table1Count FROM table1 WHERE foo=1;
SELECT Count(*) AS table2Count FROM table2 WHERE bar=2;
两个语句返回我想要的数据,但我想知道如何与两个单元返回单个表:table1Count和table2Count从一个单一的查询。
我该如何构建查询?
答
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)
+0
谢谢。这工作 – 2011-04-19 16:32:21
答
随着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
你的意思rows'的'数量和单个表两个'列'? – dotjoe 2011-04-19 16:26:46