简体   繁体   English

在 mysql 中查询范围的最佳方法

[英]best way to query ranges in mysql

I am designing a query that pull rows from a large table based on parameters expressed as ranges (specifically years).我正在设计一个查询,该查询根据表示为范围(特别是年份)的参数从大表中提取行。 There are some cases where I'll want to pull rows based on 3 specific values (say, pull customer records where customer number is #001, #002, and #003).在某些情况下,我希望根据 3 个特定值提取行(例如,提取客户编号为 #001、#002 和 #003 的客户记录)。

For the range question, I'm wondering if there is a syntax for the conditional behind the WHERE statement that works faster than the others:对于范围问题,我想知道 WHERE 语句背后的条件语法是否比其他语句运行得更快:

IN()在()

BETWEEN()之间()

high.range >= data >=low.range high.range >= 数据 >=low.range

For the IN() option, I could write a script that translate the years into a list of years from low.range to high.range inclusive.对于 IN() 选项,我可以编写一个脚本,将年份转换为从 low.range 到 high.range 的年份列表。 So, for the range 2000 to 2004, it would be IN('2000','2001','2002','2003','2004').因此,对于 2000 到 2004 的范围,它将是 IN('2000','2001','2002','2003','2004')。 This would be an extra programming step outside of MySQL, but it's not hard for me to do.这将是 MySQL 之外的额外编程步骤,但这对我来说并不难。

I realize that there are other things I can do to speed things up (like using a clustered index), but I just wanted to see if there is any difference from which sql syntax to use after the WHERE statement.我意识到我可以做其他事情来加快速度(比如使用聚集索引),但我只是想看看在 WHERE 语句之后使用的 sql 语法是否有任何区别。

Edit: sorry, I might have misinterpreted your question.编辑:对不起,我可能误解了你的问题。

I believe between in this case is the more appropriate function to in , but I'd to some benchmarking to be sure.我相信between这种情况下是更合适的 function 到in ,但我会进行一些基准测试来确定。


If you're using a TIMESTAMP, DATE or DATETIME column, you could use year :如果您使用的是 TIMESTAMP、DATE 或 DATETIME 列,则可以使用year

where year(column) > 2000 or year(column) < 2005

There are for month , week , and day functions as well.还有 for monthweekday函数。

http://dev.mysql.com/doc/refman/5.1/en/datetime.html http://dev.mysql.com/doc/refman/5.1/en/datetime.html

behind the scenes between works just like high.range >= data >=low.range作品之间的幕后就像 high.range >= data >=low.range

In(condition1, condition2, condition3) works just like (condition1 or condition2 or condition3) In(condition1, condition2, condition3) 就像 (condition1 or condition2 or condition3)

I'd expect between to work faster if the number of date is larger than 1 or 2.如果日期数大于 1 或 2,我希望 between 工作得更快。

its like (1000 > 1001) versus (1000 = 998 or 1000 = 996 or 1000 = 995 etc).它类似于 (1000 > 1001) 与 (1000 = 998 或 1000 = 996 或 1000 = 995 等)。

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

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