【问题标题】:Multiple count functions in a SELECT querySELECT 查询中的多个计数函数
【发布时间】:2011-04-09 03:49:58
【问题描述】:

我有一个这样的选择查询

select count(distinct id)*100/totalcount as freq, count (distinct id) from 
<few joins, conditions, gorup by here> .....

这会导致MySql 5.0下计算2次count吗?如果这是一个问题,我也可以计算我的应用程序中的频率。我知道Adding percentages to multiple counts in one SQL SELECT Query 中提出的解决方案,但我只是想避免嵌套查询

【问题讨论】:

    标签: mysql optimization count


    【解决方案1】:
    select count(distinct id)*100/totalcount as freq, count (distinct id) from 
    <few joins, conditions, gorup by here> .....
    

    是的,它会导致多次评估。

    DISTINCT id 上的每个记录集将为每个函数单独构建

    请注意,如果不是DISTINCTMySQL 将只使用每条记录一次(尽管在多个函数调用中)。

    由于COUNT 非常便宜,因此函数调用几乎不会增加整体查询时间。

    您可以从重写查询中受益:

    SELECT  COUNT(id) * 100 / totalcount AS freq,
            COUNT(id)
    FROM    (
            SELECT  DISTINCT id
            FROM    original_query
            ) q
    

    顺便说一句,为什么在一个查询中同时需要 GROUP BYDISTINCT?您能否按原样发布您的原始查询?

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多