如何从两个不同的表(称他们为tab1
和tab2
)中进行select count(*)
查询,从而得到如下结果:
Count_1 Count_2
123 456
我尝试过这个查询:
select count(*) Count_1 from schema.tab1 union all select count(*) Count_2 from schema.tab2
但最后只得到
Count_1
123
456
SELECT (
SELECT COUNT(*)
FROM tab1
) AS count1,
(
SELECT COUNT(*)
FROM tab2
) AS count2
FROM dual
评论
需要补充的是,想要在SQL Server中完成同样的事情,您只需要删除(上一条回答)查询的“FROM dual”部分。
只是因为一小点不一样:
SELECT 'table_1' AS table_name, COUNT(*) FROM table_1
UNION
SELECT 'table_2' AS table_name, COUNT(*) FROM table_2
UNION
SELECT 'table_3' AS table_name, COUNT(*) FROM table_3
它返回了转置的答案(每个表一行,而不是每个表一列),否则我认为没有太大区别。我认为在性能方面,它们应该是等效的。
我只在SQL Server上试过,但你可以这么做:
select (select count(*) from table1) as count1,
(select count(*) from table2) as count2
在SQL Server中,我得到了你想要的结果。
另一个稍微有些不同的方法:
with t1_count as (select count(*) c1 from t1),
t2_count as (select count(*) c2 from t2)
select c1,
c2
from t1_count,
t2_count
/
select c1,
c2
from (select count(*) c1 from t1) t1_count,
(select count(*) c2 from t2) t2_count
/
欢迎来弦圈一起翻译StackOverflow等国外编程内容
翻译原文:对多个表中进行Select count(*)查询
更多数据库相关内容:数据库 - 弦圈
更多其他趣味内容:弦圈 - 找到属于你的圈子