简体   繁体   English

MySQL:可变行最大最小查询?

[英]MySql: variable row max min query?

I have a MySql table containing stock quotes (stock_symbol, quote_date, open_price, high_price, low_price, close_price) and need to find out various max and min values: Max High/Min Low over 10/20/245/252 days. 我有一个MySql表,其中包含股票报价(stock_symbol,quote_date,open_price,high_price,low_price,close_price),并且需要找出各种最大和最小值:10/20/245/252天内的最大高/最小低。

I know how to do this using a SELECT query for each period: 我知道如何在每个期间使用SELECT查询来执行此操作:

SELECT max(high_price), min(low_price) FROM mytable WHERE stock_symbol = 'GOOG' ORDER BY quote_date DESC LIMIT 10;

Can it be done using a single SELECT statement without making the query too intense for the database server? 可以使用单个SELECT语句完成操作,而又不会使查询对数据库服务器造成太大的压力吗? Would a single SELECT statement perform better than multiple SELECT statements? 单个SELECT语句的性能会比多个SELECT语句好吗?

Any thoughts/help would be much appreciated. 任何想法/帮助将不胜感激。 Thanks! 谢谢!

Do it preferably in one statement, but the problem is only on the indexes : be sure to have an index on all columns for which you ask the min and the max or that you add in the where clause : hight_price, low_price and stock_symbol. 最好在一条语句中执行此操作,但问题仅在于索引:请确保在您要查询其最小值和最大值或在where子句中添加的所有列上都有一个索引:hight_price,low_price和stock_symbol。

With indexes, this request will be instantaneous, even for very big tables and without your LIMIT 10 使用索引,即使是非常大的表且没有LIMIT 10 ,此请求也将是瞬时的

Don't put an ORDER BY in this query : it's useless as the min and max are the same independently of the order you look at the set. 请勿在此查询中放置ORDER BY :它没有用,因为min和max相同,与您查看集合的顺序无关。

Your query should be simply 您的查询应该简单

SELECT max(high_price), min(low_price) FROM mytable WHERE stock_symbol = 'GOOG'

How to create an index : http://dev.mysql.com/doc/refman/5.0/en/create-index.html 如何创建索引: http : //dev.mysql.com/doc/refman/5.0/en/create-index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM