简体   繁体   中英

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).

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:

IN()

BETWEEN()

high.range >= data >=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. So, for the range 2000 to 2004, it would be 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.

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.

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.


If you're using a TIMESTAMP, DATE or DATETIME column, you could use year :

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

There are for month , week , and day functions as well.

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

behind the scenes between works just like high.range >= data >=low.range

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

I'd expect between to work faster if the number of date is larger than 1 or 2.

its like (1000 > 1001) versus (1000 = 998 or 1000 = 996 or 1000 = 995 etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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