来自 MySQL 中多个表的 COUNT(*)

2021-11-20 00:00:00 count mysql

如何从 MySQL 的多个表中选择 COUNT(*) 个?

How do I go about selecting COUNT(*)s from multiple tables in MySQL?

例如:

SELECT COUNT(*) AS table1Count FROM table1 WHERE someCondition
JOIN?? 
SELECT COUNT(*) AS table2Count FROM table2 WHERE someCondition
CROSS JOIN? subqueries?
SELECT COUNT(*) AS table3Count FROM table3 WHERE someCondition

目标是返回这个:

+-------------+-------------+-------------+
| table1Count | table2Count | table3Count |
+-------------+-------------+-------------+
| 14          | 27          | 0           |
+-------------+-------------+-------------+

推荐答案

你可以通过使用子查询来实现,每个 tableCount 一个子查询:

You can do it by using subqueries, one subquery for each tableCount :

SELECT
  (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
  (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count,
  (SELECT COUNT(*) FROM table3 WHERE someCondition) as table3Count

相关文章