MySQL: LIMIT the values in the GROUP_CONCAT Function

One limitation of the GROUP_CONCAT function is that you can’t directly limit it’s output. Say for example you have an order table and a products table and you wanted to list all the orders for a specific product, you could probably do this:

SELECT
    p.product_name,
    GROUP_CONCAT(o.order_id ORDER BY order_id  DESC SEPARATOR ', ') as order_ids
FROM
    product p
INNER JOIN
    orders o ON (o.product_id = p.product_id)
GROUP BY
    p.product_id

This would produce this:

+--------------------------------+------------------------+
| product_name                   | order_ids              |
+--------------------------------+------------------------+
| some laptop                    | 100223, 100266, 100298 |
+--------------------------------+------------------------+

However, say for example you only want to show the last 2 orders for this product, you can do the following:

SELECT
    p.product_name,
    SUBSTRING_INDEX(
        GROUP_CONCAT(
            o.order_id ORDER BY order_id  DESC SEPARATOR ', '
        ),', ',2
    ) as order_ids
FROM
    product p
INNER JOIN
    orders o ON (o.product_id = p.product_id)
GROUP BY
    p.product_id

The select statement does select ALL of the matching rows from the tables, however, the SUBSTRING_INDEX function truncates the amount of values by counting the ‘, ‘ character occurrences. Here’s the result:

+--------------------------------+------------------------+
| product_name                   | order_ids              |
+--------------------------------+------------------------+
| some laptop                    | 100223, 100266         |
+--------------------------------+------------------------+

Permalink: http://www.websitefactors.co.uk/mysql/2011/07/mysql-limit-the-values-in-the-group_concat-function/

This entry was posted in MySQL. Bookmark the permalink.

3 Responses to MySQL: LIMIT the values in the GROUP_CONCAT Function

  1. This was very helpful – thanks.
    Now I guess the only issue would be to test the performance of the substring_index function on large child record volumes.

  2. Henry Hayes says:

    Yes, that would be interesting to see.

  3. nexus6 says:

    just solved my problem, thx :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Notify me of followup comments via e-mail. You can also subscribe without commenting.