显示'year%'> = 2010这样的表格

时间:2012-05-20 18:24:57

标签: mysql sql-like

我有数据库的表名

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

现在我需要获得year > date('Y')-2的表格。 怎么做?

"show tables like 'year%' AND $year>='year2012';"

2 个答案:

答案 0 :(得分:5)

哎呀,这是一个不幸的架构。从长远来看,你最好取消这些与日期相关的表名。但是,您可以从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)

更新

要显示2年前和当前年份之间的表格,请使用:

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

更新2这应该与您要求的完全一致:

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 |
+------------+-----------------------------------------------------------------+

答案 1 :(得分:4)

Show tables LIKE 'year201%'

将列出2010-2019范围内的所有表格,如果您有202x:

Show tables LIKE 'year202%'