使用 MYSQL 在一个查询中选择两个表中的 COUNT [英] Select COUNT in two table in one query with MYSQL

查看:160
本文介绍了使用 MYSQL 在一个查询中选择两个表中的 COUNT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以通过一个查询选择带有两个表的 COUNT.

Is there a way i can select the COUNT with two table with one single query.

目前我有以下内容,但无法正常工作.

At the moment i have the following and it doesn't work correctly.

SELECT 
COUNT(t1.id) as t1_amount,
COUNT(t2.id) as t2_amount
FROM
table1 t1,
table2 t2

推荐答案

这是一种方法:

select (select count(*) from table1) as t1_amount,
       (select count(*) from table2) as t2_amount

这是另一种方式:

select t1.t1_amount, t2.t2_amount
from (select count(*) as t1_amount from table1) t1 cross join
     (select count(*) as t2_amount from table2) t2

您的方法不起作用,因为 from 子句中的 , 执行了 cross join.这会在两个表之间进行笛卡尔积.

Your method does not work because the , in the from clause does a cross join. This does a cartesian product between the two tables.

这篇关于使用 MYSQL 在一个查询中选择两个表中的 COUNT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆