Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在一个查询中计算两个表中的行数?_Mysql_Sql - Fatal编程技术网

Mysql 如何在一个查询中计算两个表中的行数?

Mysql 如何在一个查询中计算两个表中的行数?,mysql,sql,Mysql,Sql,我知道,如果两个表中的列数相等,可以对select语句使用UNION。另外,另一个选项是在select子句中使用子查询。我还能用什么 例如: tabel1 table2 id 1 1 2 2 3 3 我需要在一个查询中获得两个表的总行数: ...COUNT(table1.id) as tbc1, COUNT(table2.id) as tbc2... 使用子查询,如果需要从双查询添加: SELECT (SELECT COUN

我知道,如果两个表中的列数相等,可以对select语句使用
UNION
。另外,另一个选项是在select子句中使用子查询。我还能用什么

例如:

tabel1  table2
id  1       1 
    2       2
    3       3
我需要在一个查询中获得两个表的总行数:

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

使用子查询,如果需要从双查询添加

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

如果在这两个表之间进行交叉连接,将得到比实际需要多得多的行。您将得到表的笛卡尔积,因此行数将是表1中的数字乘以表2中的数字

但是,如果使用
COUNT(distinct[column])
对两个表的id值进行聚合,则仍然可以使用交叉联接

试试这个:

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

此查询统计来自第一个表的不同id值(本质上是行数),并将其与来自第二个表的行数相加。它在中起作用。

请编辑您的问题,并包括示例数据和所需结果。如前所述,不清楚您在问什么。必须改为什么?@Sahe,在您的
select
FROM
之间有两个子查询,我还不知道您的完整查询
FROM DUAL
是为了您的测试。