Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show tables like 'year%' >=2010

Tags:

mysql

sql-like

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';"
like image 963
breq Avatar asked Dec 01 '25 05:12

breq


2 Answers

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)

Update:

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())

Update 2 This should be working exactly as you ask for:

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 |
+------------+-----------------------------------------------------------------+
like image 148
Michael Berkowski Avatar answered Dec 03 '25 21:12

Michael Berkowski


Show tables LIKE 'year201%'

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

Show tables LIKE 'year202%'
like image 45
Maxim Krizhanovsky Avatar answered Dec 03 '25 21:12

Maxim Krizhanovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!