介绍
为了解决这个问题,您可以使用该INFORMATION_SCHEMA.PARTITIONS
表。对您特别有用的是 thePARTITION_DESCRIPTION
和PARTITION_NAME
字段。
来自:http ://dev.mysql.com/doc/refman/5.1/en/partitions-table.html
PARTITION_DESCRIPTION:此列用于 RANGE 和 LIST 分区。对于 RANGE 分区,它包含在分区的 VALUES LESS THAN 子句中设置的值,可以是整数或 MAXVALUE。对于 LIST 分区,此列包含分区的 VALUES IN 子句中定义的值,该子句是一个以逗号分隔的整数值列表。
对于 PARTITION_METHOD 不是 RANGE 或 LIST 的分区,此列始终为 NULL。
最后,也是非常重要的——确切的 SQL 解决方案还取决于所使用的 PARTITION类型。请参阅分区类型。
按范围划分
示例:单击以获取 SQL Fiddle
create table orders
(cost_usd double,
year int
)
PARTITION BY RANGE(year)
(
PARTITION p_2005 VALUES LESS THAN (2006),
PARTITION p_2006 VALUES LESS THAN (2007),
PARTITION p_2007 VALUES LESS THAN (2008),
PARTITION p_2008 VALUES LESS THAN (2009),
PARTITION p_2009 VALUES LESS THAN (2010),
PARTITION p_2010 VALUES LESS THAN (2011),
PARTITION p_2011 VALUES LESS THAN (2012),
PARTITION p_2012 VALUES LESS THAN (2013),
PARTITION p_2013 VALUES LESS THAN (2014)
);
insert into orders values (1039.90, 2005);
insert into orders values (459.06, 2006);
insert into orders values (033.77, 2006);
insert into orders values (6473.36, 2008);
insert into orders values (240.17, 2009);
insert into orders values (1011.20, 2013);
SQL:
SELECT DISTINCT orders.cost_usd, PartitionInfo2.PARTITION_NAME
FROM orders,
( SELECT orders.year,
min(CONVERT(p.PARTITION_DESCRIPTION,UNSIGNED INTEGER)) AS rangeMax
FROM orders,
INFORMATION_SCHEMA.PARTITIONS p
WHERE orders.year < CONVERT(p.PARTITION_DESCRIPTION,UNSIGNED INTEGER)
AND TABLE_NAME='orders'
GROUP BY orders.year) AS PartitionInfo,
INFORMATION_SCHEMA.PARTITIONS PartitionInfo2
WHERE orders.year = PartitionInfo.year AND
CONVERT(PartitionInfo2.PARTITION_DESCRIPTION,UNSIGNED INTEGER) =
PartitionInfo.RangeMax;
结果:
COST_USD PARTITION_NAME
1039.9 p_2005
459.06 p_2006
33.77 p_2006
6473.36 p_2008
240.17 p_2009
1011.2 p_2013
哈希分区
示例:单击以获取 SQL Fiddle
下面是一个通过散列进行分区的示例,但此外,我们从年份整数中减去 2000 以使分区索引从零开始。
create table orders
(cost_usd double,
year int
)
PARTITION BY HASH(year-2000) PARTITIONS 20;
从本质上讲,这意味着我们将有 20 个分区,它们将正确地适合从 2000 年到 2020 年的年份。不幸的是,更大的值会介于两者之间。
像上面这样的设置会导致更简单的解决方案。
SQL:
select cost_usd, p.PARTITION_NAME, concat('p_',orders.year) PRETTY_PNAME
from INFORMATION_SCHEMA.PARTITIONS p,
orders where
TABLE_NAME='orders' AND
PARTITION_ORDINAL_POSITION+1999 = orders.year;
结果:
COST_USD PARTITION_NAME PRETTY_PNAME
1039.9 p5 p_2005
459.06 p6 p_2006
33.77 p6 p_2006
6473.36 p8 p_2008
240.17 p9 p_2009
1011.2 p13 p_2013