Select set of all values stored in a VARCHAR based CSV field

216 Views Asked by At

I have a database table with a VARCHAR based CSV field called sizes:

id | sizes
----------
1  | '1,2,4,5'
2  | '3,4,5,6,8'
3  | '3,5,6,1'

I'd like to select the set of sizes referenced by any row in the table:

sizes
-----
  1
  2
  3
  4
  5
  6
  8

Is this possible?

N.B. I'm aware of the potential problems of CSV fields.. I'm looking at one now. I just want to know if this can be done. I'm also aware of how to normalise this data.

2

There are 2 best solutions below

2
On BEST ANSWER
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL PRIMARY KEY
,sizes VARCHAR(30) NOT NULL
);

INSERT INTO my_table VALUES
(1  ,'1,2,4,5'),
(2  ,'3,4,5,6,8'),
(3  ,'3,5,6,1');

SELECT * FROM my_table;
+----+-----------+
| id | sizes     |
+----+-----------+
|  1 | 1,2,4,5   |
|  2 | 3,4,5,6,8 |
|  3 | 3,5,6,1   |
+----+-----------+

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

  SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(sizes,',',i+1),',',-1) n 
    FROM my_table, ints i
ORDER BY n;

+---+
| n |
+---+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 8 |
+---+
1
On

mySQL does not have a split function.

Reference:

https://dev.mysql.com/doc/refman/5.6/en/string-functions.html