简体   繁体   English

一个查询中有多个表计数

[英]Multiple table counts in one query

I've done some searching around but I haven't found a clear answer and explanation to my question. 我做了一些搜索,但我没有找到一个明确的答案和解释我的问题。

I have 5 tables called table1, table2, table3, table4 and table5 and I want to do COUNT(*) on each of the tables to get the number of rows. 我有5个表,分别是table1,table2,table3,table4和table5,我想在每个表上执行COUNT(*)来获取行数。

Should I try to combine these into one query or use 5 separate queries? 我应该尝试将这些组合成一个查询还是使用5个单独的查询? I have always been taught that the least number of queries the better so I am guessing I should try to combine them into one query. 我一直被告知最少的查询数量越多越好,所以我猜我应该尝试将它们组合成一个查询。

One way of doing it is to use UNION but does anyone know what the most efficient way of doing this is and why? 一种方法是使用UNION但有谁知道最有效的方法是什么?为什么?

Thanks for any help. 谢谢你的帮助。

Assuming you just want a count(*) from each one, then 假设您只想要每个计数(*),那么

SELECT
   ( SELECT count(*) from table1 ) AS table1,
   ( SELECT count(*) from table2 ) AS table2,
   ( SELECT count(*) from table3 ) AS table3,
   etc...
)

would give you those counts as a single row. 会把这些数量作为一行给你。 The DB server would still be running n+1 queries (n tables, 1 parent query) to get those counts, but it'd be the same story if you were using a UNION anyways. 数据库服务器仍然会运行n + 1个查询(n个表,1个父查询)来获取这些计数,但如果您使用的是UNION则情况相同。 The union would produce multiple rows with 1 value in each, vs the 1 row with multiple values of the subselect method. 联合将生成多行,每行具有1个值,而对于具有多个subselect方法值的1行。

Provided you have read access to this (so rather not on shared hosting where you don't have your actual own database instance) you could read that info from the INFORMATION_SCHEMA TABLES table, that does have a TABLE_ROWS column. 如果您具有对此的读取权限(因此不是在没有实际数据库实例的共享主机上),您可以从INFORMATION_SCHEMA TABLES表中读取该信息,该表具有TABLE_ROWS列。

(Be aware of what it says for InnoDB tables there – so if you don't you MyISAM and need the precise counts, the other answer has the better solution.) (请注意它对InnoDB表的说法 - 所以如果你不是MyISAM并需要精确的计数,那么另一个答案就是更好的解决方案。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM