I've got database with tablenames
year200801
year200802
year200803
year201010
year201101
year201203
year201204
year201205
....
And now I need to get tables where year > date('Y')-2.
How to do that?
"show tables like 'year%' AND $year>='year2012';"
Ouch, this is an unfortunate schema to be working with. You're best off in the long run to do away with these date-dependent table names. However, you can get it from information_schema:
SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_SCHEMA='your_database_name'
/* LEFT() should be faster than LIKE */
AND LEFT(TABLE_NAME, 4)='year'
/* The 4 char substring in the middle of the table name is >= 2 years ago */
/* Use YEAR(NOW()) to get the current year */
AND MID(TABLE_NAME, 5, 4) >= (YEAR(NOW()) - 2)
To show tables between 2 years ago and the current year, use:
AND MID(TABLE_NAME, 5, 4) BETWEEN (YEAR(NOW()) - 2) AND YEAR(NOW())
mysql> SELECT yearstring, MID(yearstring, 5, 4) BETWEEN (YEAR(NOW()) - 2) AND YEAR(NOW()) FROM tmp;
+------------+-----------------------------------------------------------------+
| yearstring | MID(yearstring, 5, 4) BETWEEN (YEAR(NOW()) - 2) AND YEAR(NOW()) |
+------------+-----------------------------------------------------------------+
| year201001 | 1 |
| year201005 | 1 |
| year201205 | 1 |
| year201301 | 0 |
| year201112 | 1 |
| year201304 | 0 |
| year200912 | 0 |
| year200901 | 0 |
+------------+-----------------------------------------------------------------+
Show tables LIKE 'year201%'
will list all tables in the range 2010-2019, and if you have 202x:
Show tables LIKE 'year202%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With