如何从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 |
+-------------+-------------+-------------+
答案 0 :(得分:89)
您可以使用子查询来执行此操作,每个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
答案 1 :(得分:11)
您可以使用子查询执行此操作,例如:
select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count,
(SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count
答案 2 :(得分:5)
您可以使用UNION
SELECT COUNT(*) FROM table1 WHERE someCondition
UNION
SELECT COUNT(*) FROM table2 WHERE someCondition
UNION
SELECT COUNT(*) FROM table3 WHERE someCondition
答案 3 :(得分:3)
如果在特定表上没有没有条件,那么这是一种从多个表中纯粹获取行数的简单方法。
对于InnoDB,此计数为近似值。但是,对于MyISAM,该计数是准确的。
引自docs:
行数。一些存储引擎(例如MyISAM)存储 精确计数。对于其他存储引擎,例如InnoDB,此值为 一个近似值,可能与实际值相差40% 到50%在这种情况下,请使用SELECT COUNT(*)获得准确的 计数。
使用information_schema.tables
表,您可以使用:
SELECT
table_name,
table_rows
FROM
information_schema.tables
WHERE
table_name like 'my_table%';
table_name table_rows
my_table_1 0
my_table_2 15
my_table_3 30
我之所以发布此答案,是因为我在该帖子中搜索了与帖子标题匹配的此方法。希望将来能对某人有所帮助。
答案 4 :(得分:1)
尝试更改为:
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
答案 5 :(得分:0)
你可以这样做。
SELECT (select count(*) from table1) + (select count(*) from table2) as total_rows
您可以添加任意数量的表。