sqlmysqljoingroup

MySQL select and group by with concat


I have 2 table:

properties:

id,name
10,Weight
11,Color
12,Width
13,Height

product_prop:

id,product,prop,name
1,171243,10,12.56
2,171243,11,white
3,171243,12,500
4,127865,10,10.01
5,127865,11,white

My query:

SELECT p.id, p.name AS propName,
       GROUP_CONCAT(DISTINCT pp.name SEPARATOR ',') AS propValue,
       GROUP_CONCAT(DISTINCT pp.id SEPARATOR ',') AS propKey
FROM properties p 
INNER JOIN product_prop pp ON p.id = pp.prop
WHERE pp.product in (171243, 127865)
GROUP BY p.id, p.name; 

The result:

id propName propValue propKey
10 Weight 12.56,10.01 1,4
11 Color white 2,5
12 Width 500 3

The first and last row its ok. The 2nd row propKey i can see the only first found (2), because the 5 its equal the 2 (with name in product_prop table).


Solution

  • I suggest you could do this with a subselect that first identifies unique property values per property, then an outer select that does your aggregation:

    SELECT
        p.id, p.name AS propName,
        GROUP_CONCAT(upp.propValue) AS propValue,
        GROUP_CONCAT(upp.propKey) AS propKey
    FROM properties p
    INNER JOIN (
        SELECT 
            pp.prop,
            pp.name AS propValue,
            MIN(pp.id) AS propKey
        FROM product_prop pp
        WHERE pp.product in (171243, 127865)
        GROUP BY pp.prop, pp.name
    ) upp ON p.id = upp.prop
    GROUP BY p.id, p.name;