简体   繁体   English

加入计数查询mysql以提高性能

[英]Joining a count query mysql for performance

Have searched but can't find an answer which suits the exact needs for this mysql query. 已搜索但找不到适合此mysql查询确切需求的答案。

I have the following quires on multiple tables to generate "stats" for an application: 我对多个表有以下要求以为应用程序生成“统计信息”:

SELECT COUNT(id) as count FROM `mod_**` WHERE `published`='1';

SELECT COUNT(id) as count FROM `mod_***` WHERE `published`='1';

SELECT COUNT(id) as count FROM `mod_****`;

SELECT COUNT(id) as count FROM `mod_*****`;

pretty simple just counts the rows sometimes based on a status. 非常简单,只是有时根据状态来计算行数。

however in the pursuit of performance i would love to get this into 1 query to save resources. 但是,为了追求性能,我希望将此查询放入1个查询中以节省资源。

I'm using php to fetch this data with simple mysql_fetch_assoc and retrieving $res[count] if it makes a difference (pro isn't guaranteed, so plain old mysql here). 我正在使用php通过简单的mysql_fetch_assoc获取此数据,并检索$res[count]如果有区别的话(不能保证专业,因此这里是普通的旧mysql))。

The overhead of sending a query and getting a single-row response is very small. 发送查询和获取单行响应的开销非常小。

There is nothing to gain here by combining the queries. 通过组合查询,这里没有任何收获。


If you don't have indexes yet an INDEX on the published column will greatly speed up the first two queries. 如果您还没有索引,那么在已published列上使用INDEX将大大加快前两个查询的速度。

You can use something like 您可以使用类似

SELECT SUM(published=1)

for some of that. 对于其中的一些。 MySQL will take the boolean result of published=1 and translate it to an integer 0 or 1 , which can be summed up. MySQL将采用published=1的布尔结果并将其转换为整数01 ,可以将其求和。

But it looks like you're dealing with MULTIPLE tables (if that's what the ** , *** etc... are), in which case you can't really. 但是看起来您正在处理MULTIPLE表(如果这是*****等...的意思),在这种情况下您就无法做到。 You could use a UNION query, eg: 您可以使用UNION查询,例如:

SELECT ...
UNION ALL
SELECT ...
UNION ALL 
SELECT ...
etc...

That can be fired off as one single query to the DB, but it'll still execute each sub-query as its own query, and simply aggregate the individual result sets into one larger set. 可以将其作为对数据库的单个查询来触发,但它仍将每个子查询作为其自己的查询执行,并且只需将单个结果集聚合到一个更大的集中即可。

As @Halcyon said there is not much to gain here. 正如@Halcyon所说,这里没有太多收获。 You can anyway do several UNIONS to get all the result in one query 无论如何,您都可以执行几个UNIONS,以便在一个查询中获得所有结果

Disagreeing with @Halcyon I think there is an appreciable difference, especially if the MySQL server is on a different machine, as every single query uses at least one network packet. 与@Halcyon意见不同,我认为有明显的不同,尤其是如果MySQL服务器在不同的计算机上,因为每个查询至少使用一个网络数据包。

I recommend you UNION the queries with a marker field to protect against the unexpected. 我建议您将带有标记字段的查询合并,以防止意外。

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

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