3

我有带有表名的数据库

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

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

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

2 回答 2

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 |
+------------+-----------------------------------------------------------------+
于 2012-05-20T18:29:40.040 回答
4
Show tables LIKE 'year201%'

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

Show tables LIKE 'year202%'
于 2012-05-20T18:56:08.200 回答