开发者

Get the number of columns in two SQL tables in a single query?

I've written two SQL statements:

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

Both statements return the data I want, but I would like to know how to return a sing开发者_运维问答le table with two cells: table1Count and table2Count from a single query.

How do I do construct the query?


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

Gives something like:

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


With 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;

Will produce:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜