Search code examples
mysqldatabase-partitioning

On MySQL 5.1, how can I query a specific partition?


I need to run a query on a partitioned table, and I'd like a result by partition, like so:

partition     result     count
----------- ----------   ------
    p1        apples      2
    p1        oranges     3
    p2        apples      10
    p2        oranges     15

From the official MySQL docs online, if we had 5.6 or later, we'd be able to use the PARTITION clause to specify where to get the data from, but we're currently stuck at 5.1.63. Is there an easy way to do this, regardless of the partitioning scheme of the table?


Solution

  • I don't believe you can in MySQL 5.1.

    You can work around it though - whatever the partition definition you can add the same as a condition to your count.

    For example if it is a range partition on the ID column and p1 is ID < 10000, p2 ID < 20000 then

    SELECT result, partition, count(ID)
    FROM
    (
        SELECT result, ID,
          case when ID < 10000 then p1
               when ID < 20000 then p2
          .....
          end as partition
    
        FROM
          table
    ) s1
    GROUP BY partition, result