0

Suppose I have the following table:

ID|Col1    |Col2
1 |Test1   |Test12
2 |Test2   |Test22
2 |Test3   |Test32

When I use a query like:

SELECT GROUP_CONCAT(Col1) as First, GROUP_CONCAT(Col2) as Second WHERE ID=2 GROUP BY ID

It sometimes returns the GROUP_CONCAT's rearranged. For example:

ID|First      |Second
2 |Test2,Test3|Test32,Test22

While I would expect it to return:

ID|First      |Second
2 |Test2,Test3|Test22,Test32

As you can see, it switched the concatenated values in the column named 'Second'. How can I prevent this from happening?

TVA van Hesteren
  • 1,031
  • 3
  • 20
  • 47

2 Answers2

1

If you want the values in a particular order, then use order by:

SELECT GROUP_CONCAT(Col1 ORDER BY Col1) as First,
       GROUP_CONCAT(Col2 ORDER BY col2) as Second
FROM t
WHERE ID = 2
GROUP BY ID;

In general, SQL deals with unordered sets. If you want things in a particular order, then you need to explicitly specify the ordering.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • This will only work assuming that the values within the columns have the same ordening structure like A-B-C A-B-C. When it is A-B-C B-A-C it will fail right? – TVA van Hesteren Mar 31 '17 at 13:51
  • @TVAvanHesteren . . . This will return the values in a canonical ordering -- alphabetically. If you have another column that specifies the ordering, you can use that in the `ORDER BY`. – Gordon Linoff Mar 31 '17 at 23:01
  • What I want to achieve is that the CONCAT_GROUP Col2 returns the values in the same order as the CONCAT_GROUP Col1 which I can't achieve so far. I tried ordening both on Col1, both on their own list so Col2 by Col2, Col1 by Col1. But still it won't match the found rows in indexes of the returned groups – TVA van Hesteren Apr 01 '17 at 10:23
1

This table is missing common column (PK) to sort in group_concat.

ID|GroupID|Col1 |Col2

1|1 |Test1 |Test12

2|2 |Test2 |Test22

3|2 |Test3 |Test32

SELECT GROUP_CONCAT(Col1 ORDER BY ID) as First,
       GROUP_CONCAT(Col2 ORDER BY ID) as Second
FROM t
WHERE GroupID = 2
GROUP BY GroupID;

This will retain the order of group concat of col1 and col2.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
SQL.RK
  • 157
  • 4
  • Yes it will, however I don't have the option to add another column. +1 for the order by within the GROUP_CONCAT though, didn't realized that it was possible – TVA van Hesteren Mar 31 '17 at 13:50