MySQL对多个表进行COUNT(*)查询
问题
我该如何从 MySQL 中的多个表中选择 COUNT(*)?
比如说:
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 |
+-------------+-------------+-------------+
回答1
你可以通过使用子查询来实现它,每个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
你可以使用子查询来做到这一点,比如:
select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count,
(SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count
回答3
你可以使用联合查询
SELECT COUNT(*) FROM table1 WHERE someCondition
UNION
SELECT COUNT(*) FROM table2 WHERE someCondition
UNION
SELECT COUNT(*) FROM table3 WHERE someCondition
内容来源于StackOverflow, 遵循 CCBY-SA 4.0 许可协议进行翻译与使用。原文链接:COUNT(*) from multiple tables in MySQL
暂无评论,来发布第一条评论吧!