user1757037
user1757037

Reputation: 1

MYSQL - ORDER AND CONCAT 2 or more FILEDS

I Have this situation and I need the second table as a result. I have to Order the filels "TYPEn" and concat () them.

+----+------+-------+-------+-------+-------+
| ID | TYPE1| TYPE2 | TYPE3 | TYPE4 | TYPE5 |
+----+------+-------+-------+-------+-------+
|  1 | D    | C     |    A  |       |       |
|  2 | F    | D     |    C  |       |       |
|  3 | C    | L     |    A  |       |       |
|  4 | T    | O     |    M  |       |       |
+----+------+-------+-------+-------+-------+



+----+------+
| ID | RES  |
+----+------+
|  1 | ACD  |
|  2 | CDF  |
|  3 | ACL  |
|  4 | MOT  |
+----+------+

Upvotes: 0

Views: 481

Answers (1)

eggyal
eggyal

Reputation: 125865

That you are trying to perform this operation at all is highly indicative of a denormalised schema. You should consider normalising your schema, which would greatly simplify this operation.

As things stand, you can effectively (albeit very inefficiently) create normalised data structures on the fly and then use them:

SELECT ID, GROUP_CONCAT(TYPE ORDER BY TYPE SEPARATOR '') RES FROM (
  SELECT ID, TYPE1 TYPE FROM myTable
  UNION ALL
  SELECT ID, TYPE2 FROM myTable
  UNION ALL
  SELECT ID, TYPE3 FROM myTable
) t GROUP BY ID

See it on sqlfiddle.

Upvotes: 2

Related Questions