简体   繁体   English

两个范围之间的MySQL查询

[英]MySQL Query Between Two Ranges

I need help with a query. 我需要查询方面的帮助。 I am taking input from a user where they enter a range between 1-100. 我正在接受用户输入,他们输入的范围是1-100。 So it could be like 30-40 or 66-99. 因此可能是30-40或66-99。 Then I need a query to pull data from a table that has a high_range and a low_range to find a match to any number in their range. 然后,我需要一个查询以从具有high_range和low_range的表中提取数据,以查找与其范围内的任何数字匹配的数据。

So if a user did 30-40 and the table had entries for 1-80, 21-33, 32-40, 40-41, 66-99, and 1-29 it would find all but the last two in the table. 因此,如果用户执行30-40,并且表中包含1-80、21-33、32-40、40-41、66-99和1-29的条目,则它将找到表中除最后两个之外的所有条目。

What is the easiest why to do this? 为什么最容易这样做?

Thanks 谢谢

如果我理解正确(即您想要与用户输入的范围重叠的任何范围),我会说:

SELECT * FROM table WHERE low <= $high AND high >= $low

What I understood is that the range is stored in this format low-high . 我了解的是,范围以这种格式存储为low-high If that is the case, then this is a poor design. 如果真是这样,那么这是一个较差的设计。 I suggest splitting the values into two columns: low , and high . 我建议将值分为两列: lowhigh

If you already have the values split, you can use some statement like: 如果已经拆分了值,则可以使用以下语句:

SELECT * FROM myTable WHERE low <= $needleHigherBound AND high >= $needleLowerBound

If you have the values stored in one column, and insist they stay so, You might find the SUBSTRING_INDEX function of MySQL useful. 如果您将值存储在一个列中,并坚持要保持SUBSTRING_INDEX ,那么您可能会发现MySQL的SUBSTRING_INDEX函数很有用。 But in this case, you'll have to write a complicated query to parse all the values of all the rows, and then compare them to your search values. 但是在这种情况下,您将必须编写一个复杂的查询来解析所有行的所有值,然后将它们与搜索值进行比较。 It seems like a lot of effort to cover up a design flaw. 似乎需要付出很多努力才能掩盖设计缺陷。

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

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