代码之家  ›  专栏  ›  技术社区  ›  Midhat

SELECT查询中的多个计数函数

  •  2
  • Midhat  · 技术社区  · 15 年前

    我有这样一个选择查询

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

    在MySQL5.0下,这会导致2次计数计算吗?如果这是个问题,我也可以在我的应用程序中计算频率。我知道本报告提出的解决办法 Adding percentages to multiple counts in one SQL SELECT Query 但我只想避免嵌套查询

    1 回复  |  直到 9 年前
        1
  •  2
  •   Quassnoi    15 年前
    select count(distinct id)*100/totalcount as freq, count (distinct id) from 
    <few joins, conditions, gorup by here> .....
    

    上的每个记录集 DISTINCT id 将为每个功能分别构建

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

    COUNT 非常便宜,函数调用几乎不增加任何查询时间。

    将查询重写为:

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

    GROUP BY 独特的 在一个查询中?你能按原样把你最初的问题贴出来吗?