0

Is it possible to sort elements from group_concat as integer values, not string values?

The order result is 1,11,12,3,5,6..
I Need 1,3,5,6,11,12...

I try with cast, but des not works:

GROUP_CONCAT( .. 
  ORDER BY 
   IF(attribute_value_order="order",
      CAST(value_order AS SIGNED),
           value_name) 
  ASC SEPARATOR "|" ) as value
2
  • maybe you can zerofill the order values Commented Aug 14, 2014 at 9:36
  • I solve this with a LPAD, but is normal this behavior? or I do something wrong? Commented Aug 14, 2014 at 9:51

1 Answer 1

1

Just running a test:

The table:

CREATE TABLE IF NOT EXISTS `gc` (
  `ord` int(11) NOT NULL,
  `group` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `gc` (`ord`, `gr`) VALUES
(1, 0), (2, 0), (1, 0), (2, 0), (11, 0), (12, 0), (3, 0), (5, 0),
(1, 1), (2, 1), (1, 1), (2, 1), (11, 1), (12, 1), (3, 1), (5, 1);

I ran SELECT GROUP_CONCAT(ord ORDER BY ord) FROM gc GROUP BY gr and the result isjust as you want it:

1,1,2,2,3,5,11,12

But if you use VARCHAR for the ord column, the result for the exact same query is

1,1,11,12,2,2,3,5

But The Query SELECT GROUP_CONCAT(ord ORDER BY CAST(ord AS SIGNED)) FROM gc GROUP BY gr returns again

1,1,2,2,3,5,11,12

I tested this with MySQL 5.6.11

UPDATE

You cannot change the ORDER BY clause in a GROUP_CONCAT with an IF, but you can change the whole GROUP_CONCAT for different groups by writing the IF in front of the GROUP_CONCAT

SELECT 
  gr, 
  IF(gr = 0, 
     GROUP_CONCAT(ord ORDER BY CAST(ord AS SIGNED)),
     GROUP_CONCAT(ord ORDER BY ord ) ) AS res
FROM gc 
GROUP BY gr

results in

gr  res     
0   1,1,2,2,3,5,11,12
1   1,1,11,12,2,2,3,5
Sign up to request clarification or add additional context in comments.

2 Comments

Try with an IF inside GROUP_CONCAT. My query is only a simple example, I have big query that join attributes, values and products. The values of atributes of some products. Attribute entity have a field with the order field of they values (name or order numeric). Depending of the attribute the values are sorted form one or other field. I doesn't have problems to do this with other system, but I was curious if this problem could solve.
Maybe you can write yout if before the Group_concat. The problem seems to be, that you cannot change the order for every item that will be concatenated. But since your IF is not effected by the items you concat, you can use IF(..., GROUP_CONCAT(...), GROUP_CONCAT(...)) AS groupconcat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.