简体   繁体   English

如何在一个查询中计算来自两个表的行?

[英]How to count rows from two tables in one query?

I know that one can use UNION on a select statement if count of columns in two tables is equal. 我知道,如果两个表中的列数相等,则可以在select语句上使用UNION Also, another option is using sub-query in the select clause. 另外,另一个选择是在select子句中使用子查询。 What else can I use? 我还能使用什么?

Example: 例:

tabel1  table2
id  1       1 
    2       2
    3       3

I need to get the number of total rows from both tables in one query: 我需要在一个查询中从两个表中获取总行数:

...COUNT(table1.id) as tbc1, COUNT(table2.id) as tbc2...

Use sub-queries and if it needs add FROM DUAL : 使用子查询,如果需要添加FROM DUAL

SELECT 
    (SELECT COUNT(*) FROM TABLE1) As Table1Count, 
    (SELECT COUNT(*) FROM TABLE2) As Table2Count
[FROM DUAL]

If you do a cross join between the two tables, you'll get a lot more rows than you really need here. 如果在两个表之间进行交叉联接,则会得到比实际需要更多的行。 You'll get a cartesian product of the tables, so the number of rows would be the number in table one multiplied by the number in table two. 您将获得表的笛卡尔积,因此行数将是表1中的数字乘以表2中的数字。

However, a cross join can still be used if you preform aggregation on the id values of the two tables, using COUNT(distinct [column]) . 但是,如果使用COUNT(distinct [column])对两个表的id值执行聚合,则仍然可以使用交叉COUNT(distinct [column])

Try this: 尝试这个:

SELECT COUNT(distinct t1.id) + COUNT(distinct t2.id) AS totalRows
FROM firstTable t1, secondTable t2;

This query counts the distinct id values that come from the first table (which is essentially the number of rows) and adds it with the number of rows from the second table as well. 此查询计算来自第一个表的不同ID值(本质上是行数),并将其与第二个表中的行数相加。 It worked in SQL Fiddle . 它在SQL Fiddle中起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM