mysql - SQL VIEW简化/解决更快的查询

标签 mysql sql mariadb

我正在尝试分解并重新编写由一位早已离去的开发人员创建的 View 。查询需要超过三分钟的时间才能访问,我假设来自所有 CONCAT。

CREATE VIEW `active_users_over_time` AS 
select 
   `users_activity`.`date` AS `date`,
   time_format(
        addtime( 
            concat(`users_activity`.`date`,' ',`users_activity`.`time`),
            concat('0 ',sec_to_time(`users_activity`.`duration_checkout`),'.0')
        ),'%H:%i:%s') AS `time`,
   `users_activity`.`username` AS `username`,
   count(addtime(concat(`users_activity`.`date`,' ',`users_activity`.`time`),
   concat('0 ',sec_to_time(`users_activity`.`duration_checkout`),'.0'))) AS `checkouts` 
from `users_activity` 
group by 
   concat(
       addtime(
             concat(`users_activity`.`date`,' ',`users_activity`.`time`),
             concat('0 ',sec_to_time(`users_activity`.`duration_checkout`),'.0')
       ),
       `users_activity`.`username`);

数据来自SQL表:

CREATE TABLE `users_activity` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `featureid` smallint(5) unsigned NOT NULL,
  `date` date NOT NULL,
  `time` time NOT NULL,
  `duration_checkout` int unsigned NOT NULL,
  `update_date` date NOT NULL,
  `username`  varchar(255) NOT NULL,
  `checkout` smallint(5) unsigned NOT NULL,
  `licid` smallint(5) unsigned NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `featureid_licid_username` (`featureid`,`licid`,`date`,`time`,`username`),
  FOREIGN KEY(featureid) REFERENCES features(id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

我很难确定到底需要什么,不需要什么。

有人有什么想法吗?谢谢。

最佳答案

我认为这完成了原始查询所做的一切,跳过了一堆冗余步骤:

select `date`
, `time`
, `username`
, count(1) as `checkouts`
from
(
  select 
   `users_activity`.`date` AS `date`
   ,time_format(
     addtime(`users_activity`.`date`,`users_activity`.`time`)
     + interval `users_activity`.`duration_checkout` second
     ,'%H:%i:%s'
   ) AS `time`
   ,`users_activity`.`username` AS `username`
  from `users_activity` 
) x
group by `username`, `date`, `time`

您可能还想查看表上有哪些索引,看看是否可以在其他地方进行优化(例如,如果您还没有在用户名和日期字段上建立索引,您将获得很多好处此查询通过添加一个)。

关于mysql - SQL VIEW简化/解决更快的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644456/

相关文章:

sql - MySQL 跨表计数(*) 查询帮助

mysql - SQL累积前几天的结果,同时获取过去24小时内的记录数

mysql - 组 ID 是关键。如何从一组中获取查询并将其附加到另一组

mysql - mysql 数据库中的数据格式不正确

mysql - 我想选择一个特定的数据,但查询结果给出了sqlite中的所有列

Mysql:一个表的一个字段和另一个表的两个字段之间的多重关系

mysql - 将 Windows MySQL Workbench 8.0 与 Mariadb 和 PAM 身份验证结合使用

MySQL 查询要过滤的多列?

mysql - 优化了 3 个表的连接查询

mysql - 按随机非空条目分组