sql请求检索每天的最大,最小第一个和最后一个记录

时间:2018-08-17 09:05:49

标签: mysql sql

我想获取数据库mysql中的第一条和最后一条记录的最小值和最大值。 我正在寻找一个耗时不超过15分钟的高性能查询。

我已经测试过:

SELECT
  MIN(low),
  MAX(high),
  CONCAT(YEAR(date), "-", WEEK(date)) AS myweek,
  (select open from prices m where WEEK(m.date)=WEEK(prices.date) order by date LIMIT 1) as first_open,
  (select close from prices m where WEEK(m.date)=WEEK(prices.date) order by date desc LIMIT 1) as last_close
FROM prices
GROUP BY myweek
ORDER BY date;

但是我有一个错误:

Erreur dans la requête (1055): Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'siteinfo.prices.date' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我无法更正此错误,因为我无权访问conf文件,也没有用户超级管理员。

我也测试过:

select 
DATE_FORMAT(date, "%Y" "%m" "%d") as datetime, 
(select open from prices m where m.date like CONCAT(YEAR(datetime), "-[0]", Month(datetime), "-[0]", DAY(datetime), "%") and fk_cryptoid = 'f2a0ba90-93df-11e8-af1b-5968de90d63b'  order by date ASC LIMIT 1) as open,
(select close from prices m where m.date like CONCAT(YEAR(datetime), "-[0]", Month(datetime), "-[0]", DAY(datetime), "%") and fk_cryptoid = 'f2a0ba90-93df-11e8-af1b-5968de90d63b'  order by date DESC LIMIT 1) as close,
min(low) as low, 
max(high) as high 
from prices
where fk_cryptoid = 'f2a0ba90-93df-11e8-af1b-5968de90d63b' 
 GROUP BY datetime;

,但是CONCAT()不会返回日期和月份,并且零分别为:2018-1-2,而不是2018-01-02。那么此请求将花费太多时间。

表价格模型:

id  int(11) Incrément automatique    
close   double NULL  
open    double NULL  
low double NULL  
high    double NULL  
date    datetime NULL    
createdAt   datetime     
updatedAt   datetime     
fk_cryptoid char(36) NULL 

1 个答案:

答案 0 :(得分:0)

如果它对您有用,那么我建议您使用group_concat() / substring_index()技巧:

SELECT MIN(low), MAX(high),
       CONCAT(YEAR(date), '-', WEEK(date)) AS myweek,
       SUBSTRING_INDEX(GROUP_CONCAT(open ORDER BY date), ',', 1) as first_open,
       SUBSTRING_INDEX(GROUP_CONCAT(close ORDER BY date DESC), ',', 1) as last_close
FROM prices
GROUP BY myweek
ORDER BY date;

注意:

  • first_openlast_close列将是字符串。
  • 假设openclose没有逗号。如果是这样,请使用其他分隔符。
  • GROUP_CONCAT()的默认内部限制约为1,000个字节。您可以使用服务器参数进行调整。
相关问题