简体   繁体   English

使用LIKE查询MySQL范围

[英]Querying a MySQL range using LIKE

I have a ref field in my mysql table that holds values that look like '0-0-at-3267-201411041356'. 我的mysql表中有一个ref字段,其中保存着看起来像'0-0-at-3267-201411041356'的值。 The first part (0-0-at-3267-) varies in length and values and the second part (201411041356) is a date/time that references a creation date/time. 第一部分(0-0-at-3267-)的长度和值有所不同,第二部分(201411041356)是引用创建日期/时间的日期/时间。 Everything that this code is used for is checked to see if it falls within a certain date/time period, such as between 201409010000 and 201508312359. 会检查此代码用于的所有内容,以查看其是否在某个日期/时间段内,例如在201409010000和201508312359之间。

Normally I can simply explode the data and then measure but for this instance it would make it too clunky. 通常,我可以简单地分解数据然后进行测量,但是在这种情况下,它将使数据过于笨重。 So what I want to do is use the LIKE function in my query like so LIKE '%201411041356' but I want to use it with the > and < symbols, so the full query looking something like SELECT * FROM my_table WHERE ref LIKE > '%201409010000' AND ref LIKE < '%201508312359' 因此,我想在查询中使用LIKE函数,例如LIKE '%201411041356'但我想将其与><符号一起使用,因此完整查询看起来像SELECT * FROM my_table WHERE ref LIKE > '%201409010000' AND ref LIKE < '%201508312359'

Any ideas would be most welcome! 任何想法都将受到欢迎! BTW, this has always been the way this data has been stored and there's lots of it so changing it is not an option. 顺便说一句,这一直是数据存储的方式,而且数据很多,因此更改它不是一种选择。

SELECT *
FROM my_table 
WHERE SUBSTRING(ref,-12) BETWEEN '201409010000' AND '201508312359'` 

would work better for substracting last 12 characters. 减去最后12个字符会更好。

您可以在子字符串之间使用,例如:

SELECT * FROM my_table WHERE SUBSTRING(ref,-12) BETWEEN '201409010000' AND '201508312359'

Because You wrote that first part may have different lenght so You have strip substring starting from the end. 因为您写的第一部分的长度可能不同,所以您从结尾开始有子字符串。

So Your quwery may looks like: 因此,您的quwery可能类似于:

SELECT * FROM table 
WHERE
SUBSTRING('ref', -12) > $from
AND 
SUBSTRING('ref', -12) < $to

如果您只想按日期进行度量,请使用:

left(right(ref, 12), 8)

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

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