简体   繁体   中英

Regular expressions on strings in SQL statement

I have a table with following columns and sample data

File Name            | Status
'xxx_2015-07-20.csv' | Completed
'xxx_2015-07-19.csv' | Completed
'xxx_2015-07-18.csv' | Failed
.
.
'xxx_2015-06-01.csv' | Failed

Now I have two scenarios in my application (PHP-MySQL):

1) I have to fetch the status of today's file. I can do it like this:

select status from myTable where file_name like '%date(Y-m-d)%';

2) I want to fetch the status of all files generated since 1 month from today. Suppose today is 2015-07-20, then files from 2015-06-20 should show up. Since there is no date column, I can't apply comparison operator and get the results. I believe it will need some playing with regular expressions.

I am not familiar with regular expressions, so any help on this would be much appreciated.

If the pattern is same ie xxx_2015-07-20.csv you can use substring_index function to get the date value as

mysql> select substring_index(substring_index('xxx_2015-07-20.csv','_',-1),'.',1) as d;
+------------+
| d          |
+------------+
| 2015-07-20 |
+------------+

Now using the same you can have the select statement as

select status from myTable 
    where
      substring_index( 
         substring_index(file_name,'_',-1),
         '.',1
       ) = curdate();

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