33

我计算来自多个列的值,如下所示:

SELECT COUNT(column1),column1 FROM table GROUP BY column1
SELECT COUNT(column2),column2 FROM table GROUP BY column2
SELECT COUNT(column3),column3 FROM table GROUP BY column3

例如,这会返回 column1 array(attr1 => 2000, attr2 => 3000...) (每列都有特定的值和少数值)。问题是我的应用程序中的“表”可能是一个带有一些连接和 where 子句的查询,这可能需要 0.1 秒。通过做所有这些计算,“表”每次都会重新计算,这是不必要的。有什么方法可以通过一个查询获取我想要的结果,或者“缓存”生成表的查询?否则我相信非规范化将是这里唯一的解决方案。我想要与上述查询相同的结果。我正在使用 mysql-myisam。

4

6 回答 6

51

如果不了解数据的上下文/结构,很难知道如何为您提供帮助,但我相信这可能会对您有所帮助:

SELECT 
     SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
    ,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
    ,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table
于 2012-11-02T15:26:20.623 回答
9

一种解决方案是将其包装在子查询中

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s
于 2012-10-02T15:15:04.613 回答
3
select tab1.name,
count(distinct tab2.id) as tab2_record_count
count(distinct tab3.id) as tab3_record_count
count(distinct tab4.id) as tab4_record_count
from tab1
left join tab2 on tab2.tab1_id = tab1.id
left join tab3 on tab3.tab1_id = tab1.id
left join tab4 on tab4.tab1_id = tab1.id
于 2015-07-03T06:38:03.237 回答
1

您没有说您使用的是哪个数据库服务器,但如果临时表可用,它们可能是最好的方法。

// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1  
SELECT COUNT(column2),column2 FROM #table GROUP BY column2  
SELECT COUNT(column3),column3 FROM #table GROUP BY column3  
// drop may not be required
drop table #table
于 2012-10-02T15:18:16.607 回答
0
    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 
于 2016-10-05T08:04:48.353 回答
0

SELECT COUNT(col1 OR col2) FROM [table_name] GROUP BY col1,col2;

于 2020-12-09T03:44:46.880 回答