我从多个列中计算值,如下所示:

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

This returns for example for column1 array(attr1 => 2000, attr2 => 3000...) (Each column has specific and few values). The problem is that "table" in my application can be a query with some joins and where clauses, that may take 0.1sec. By doing all that counts "table" is computed each time again which is not necessary. Is there any way to take the results i want with one query, or "cache" the query that produces table? Otherwise i believe denormalization would be the only solution here. And i want the same results with the above queries. I am using mysql-myisam.

推荐答案

在不了解数据的上下文/ struct 的情况下,很难知道如何帮助您,但我相信这可能会帮助您:

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

Database相关问答推荐

为什么Hibernate会为@JoinTable的双向@OneToMany关系生成一个复杂的子查询?

Kusto:从一个表中复制行并追加到同一集群中的另一个表中

芭蕾舞女演员坚持 1:N 关系

postgres 索引扫描的启动成本(postgresql 书的内部 struct )

微服务:每个实例或每个微服务的数据源?

用于 sql server 的免费国家、城市数据库

错误:mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication

Postgresql 从多个表中删除多行

使用varchar作为主键?

处理hibernate entities上的数据库视图的优雅方法?

连接字符串中超时

Mysql用户创建脚本

MySQL 数据库中列名中的连字符

在 SQLite 数据库中加入 3 个表

MySQL 中 NOW()、SYSDATE() 和 CURRENT_DATE() 之间的区别

Redis Pub/Sub 和 Redis Stream 之间的主要区别是什么?

Rails 新手,设置 db 然后运行 ​​rake db:create/migrate

MySQL 整数 0 与 NULL

Hibernate hbm2ddl.auto 默认值

如何在数据库中表示树状 struct