我有几张(记录)表,每月一张,全年12张。 表格模式是:usage_YYYY_MM(所以'是:usage_2012_11,usage_2012_12,usage_2013_01等)
我想要做的是在单个视图中组合这些表的内容。有时整整一年,有时候过去N个月...... 在视图中我会使用类似的东西:
(SELECT order_id, SUM(`usage`) as total, created FROM usage_2012_05 GROUP BY order_id)
UNION ALL
(SELECT order_id, SUM(`usage`) as total, created FROM usage_2012_06 GROUP BY order_id)
UNION ALL
(SELECT order_id, SUM(`usage`) as total, created FROM usage_2012_07 GROUP BY order_id)
ORDER BY created;
由于我不希望每个月都向特定视图添加新表,所以我曾想过在循环中执行此操作。我一直在窥探,已经明白我应该使用像SELECT GROUP_CONCAT这样的东西。这是我到目前为止所得到的:
SET @resultQuery = NULL;
SELECT
GROUP_CONCAT(
CONCAT('SELECT order_id, `usage` as used, created FROM ', table_name )
SEPARATOR '\r\nUNION\r\n'
)
INTO
@resultQuery
FROM
information_schema.`TABLES`
WHERE
table_name LIKE "usage_%"
ORDER BY
table_name DESC LIMIT 2;
PREPARE stmt FROM @resultQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
现在,虽然这个DOES给了我整个数据集,但最后一点(ORDER BY table_name DESC LIMIT 2)似乎不起作用......所以,我仍然不完全在那里..
为什么ORDER BY DESC和LIMIT不起作用?我应该采用不同的方法吗?
BTW:没有找到关于“usage_”表的规范化的良好意见。我们很清楚这一点,但有特定的(传统)理由希望他们这样..