How do I go about selecting COUNT(*)s from multiple tables in MySQL?
如何从MySQL中的多个表中选择COUNT(*)?
Such as:
如:
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
Edit:
编辑:
The goal is to return this:
目标是返回:
+-------------+-------------+-------------+
| table1Count | table2Count | table3Count |
+-------------+-------------+-------------+
| 14 | 27 | 0 |
+-------------+-------------+-------------+
4 个解决方案
#1
74
You can do it by using subqueries, one subquery for each tableCount :
您可以使用子查询来执行此操作,每个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
#2
10
You can do this with subqueries, e.g.:
您可以使用子查询执行此操作,例如:
select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count,
(SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count
#3
3
You can use UNION
你可以使用UNION
SELECT COUNT(*) FROM table1 WHERE someCondition
UNION
SELECT COUNT(*) FROM table2 WHERE someCondition
UNION
SELECT COUNT(*) FROM table3 WHERE someCondition
#4
2
Try changing to:
尝试更改为:
SELECT
COUNT(table1.*) as t1,
COUNT(table2.*) as t2,
COUNT(table3.*) as t3
FROM table1
LEFT JOIN tabel2 ON condition
LEFT JOIN tabel3 ON condition
#1
74
You can do it by using subqueries, one subquery for each tableCount :
您可以使用子查询来执行此操作,每个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
#2
10
You can do this with subqueries, e.g.:
您可以使用子查询执行此操作,例如:
select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count,
(SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count
#3
3
You can use UNION
你可以使用UNION
SELECT COUNT(*) FROM table1 WHERE someCondition
UNION
SELECT COUNT(*) FROM table2 WHERE someCondition
UNION
SELECT COUNT(*) FROM table3 WHERE someCondition
#4
2
Try changing to:
尝试更改为:
SELECT
COUNT(table1.*) as t1,
COUNT(table2.*) as t2,
COUNT(table3.*) as t3
FROM table1
LEFT JOIN tabel2 ON condition
LEFT JOIN tabel3 ON condition