我在数据库中有一列存储用户年龄的列,比如5-10、10-18、18-25……
现在,我想要编写一个查询来获取年龄与此范围匹配的列。
例如,如果我将age传递为12,它应该获取适合10-18范围内的列。如果我将age作为10传递,它应该获取适合5-10范围内的列。
但事实是,我将范围存储为varchar类型(中间有一个连字符)。
因此,我很好奇如何实现这一点,以及如何构造查询。
发布于 2011-03-11 20:25:40
您可以使用SUBSTRING_INDEX拆分值
SELECT * FROM `yourtable` WHERE 5 BETWEEN SUBSTRING_INDEX(`agespan`,'-', 1) AND SUBSTRING_INDEX(`agespan`,'-', -1) 此查询的agespan是包含5-10、12-18的列。
SUBSTRING_INDEX(agespan,'-',1)匹配第一次出现-之前字符串中的所有内容
SUBSTRING_INDEX(agespan,'-',-1)匹配字符串中最后一次出现-之后的所有内容
发布于 2011-03-11 19:36:48
我认为这将是容易的(如果你可以)更改一点数据模型,并添加到范围的数值字段,例如:
| MIN_AGE | MAX_AGE |
5 10
11 18因此,您可以在这两个值之间进行选择。
我也建议你不要对两个块使用相同的值,例如,如果你有5-10,下一个应该是11-18。
如果您不能更改数据模型,我可能会获取数据并在PHP中处理它,或者在数据库中创建一些存储过程来处理数据,但这不是一项微不足道的任务。
EDIT 1:
如果你没有太多的范围,你可以把它们都放到你的PHP代码中,然后使用下面的表达式将"5-10“字符串转换成两个整数:
"""
^ # Assert position at the beginning of a line (at beginning of the string or after a line break character)
( # Match the regular expression below and capture its match into backreference number 1
[0-9] # Match a single character in the range between “0” and “9”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
- # Match the character “-” literally
( # Match the regular expression below and capture its match into backreference number 2
[0-9] # Match a single character in the range between “0” and “9”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
$ # Assert position at the end of a line (at the end of the string or before a line break character)
"""
^([0-9]+)-([0-9]+)$这样,您将获得两个捕获组,第一组具有最小值,第二组具有最大值。此时很容易检查您拥有的值是否在该范围内。
我希望这对你有意义,如果没有,请让我知道:)
发布于 2011-03-11 20:25:37
您需要将字符串拆分为两部分,"-“之前的部分和"-”之后的部分。
SELECT range INTO @Range FROM ATable WHERE ...
/* or for a quick test: SET @range = "5-10"; */
SET @dash_pos = LOCATE("-",@Range);
SET @from = LEFT(@Range,@dash_pos-1);
SET @to = RIGHT(@Range, LENGTH(@Range) - (@dash_pos));
/*debug code to test if @from and @to are filled correctly*/
SELECT @Range, @dash_pos, @from, @to;
/*remove in production*/
SELECT * FROM tableName
WHERE tablename.age BETWEEN @from AND @to;https://stackoverflow.com/questions/5272320
复制相似问题