如何在MySQL中查询它的名称时从分区中进行选择

时间:2015-03-12 10:45:32

标签: mysql sql select partition

我有类似这样的问题: how to select dynamically in select * from <table_name> partiton (Partition name)?但是在Mysql中。

使用时:

select concat('p', year(now()), month(now()));

回应是:

+----------------------------------------+
| concat('p', year(now()), month(now())) |
+----------------------------------------+
| p20153                                 |
+----------------------------------------+

尝试使用时:

select max(ttime) from table partition(select concat('p', year(now()), month(now()))));

我收到错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select concat('p', year(now()), month(now()))))' at line 1

当然尝试select max(ttime) from table partition(p20153)按预期工作时:

root@localhost [tom]> select max(ttime) from table partition(p20153);
+---------------------+
| max(ttime)          |
+---------------------+
| 2015-03-16 09:54:34 |
+---------------------+
1 row in set (0.00 sec)

请注意,动态部分是分区名称而不是表名称。 样本数据:

root@localhost [tom]> select id, ttime, value from table partition(p20153) limit 10;
+----------+---------------------+----------+
| id       | ttime               | value    |
+----------+---------------------+----------+
| 13964275 | 2015-03-01 00:05:11 | 16450824 |
| 13964291 | 2015-03-01 00:08:12 | 15964352 |
| 13964332 | 2015-03-01 00:09:42 | 14701984 |
| 13964379 | 2015-03-01 00:13:27 |    26128 |
| 13964411 | 2015-03-01 00:16:29 | 11073744 |
| 13964452 | 2015-03-01 00:20:34 | 14747992 |
| 13964486 | 2015-03-01 00:23:35 |   177800 |
| 13964507 | 2015-03-01 00:26:36 | 16786408 |
| 13964542 | 2015-03-01 00:28:28 |  8749552 |
| 13964571 | 2015-03-01 00:31:30 | 16932344 |
+----------+---------------------+----------+
10 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:0)

您在查询中使用的语法不正确尝试此

select max(ttime) from 
(
  select concat('p', year(now()), month(now())) as ttime 
)
temp