= 2010 I have a database with tablenames year200801 year200802 year200803 year201010 year201101 year201203 year2012...">

Show tables like "year%"> = 2010

I have a database with tablenames

year200801
year200802
year200803
year201010
year201101
year201203
year201204
year201205
....

And now I need to get the tables where year > date('Y')-2. How to do it?

"show tables like 'year%' AND $year>='year2012';"
+3
source share
2 answers

Oh, this is a bad scheme to work on. Ultimately, your best bet is to end these date-dependent 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)

Update:

To show tables between 2 years earlier and the current year, use:

  AND MID(TABLE_NAME, 5, 4) BETWEEN (YEAR(NOW()) - 2) AND YEAR(NOW())

Update 2 This should work exactly as you ask:

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 |
+------------+-----------------------------------------------------------------+
+5
source
Show tables LIKE 'year201%'

will display all the tables in the range 2010-2019, and if you have 202x:

Show tables LIKE 'year202%'
+4
source

All Articles