This topic is locked

Split comma-separated values to rows at database level (for example Tags)

8/17/2023 1:36:26 PM
PHPRunner General questions
Davor Geci authorDevClub member

Here is a one way of how to turn this:img alt

To this:img alt

Fiddle link for playing and testing:https://dbfiddle.uk/3EB1WbNI

And if the fiddle goes away here is the code:
`-- Create the table and insert data
CREATE TABLE your_table (
id INT PRIMARY KEY,
tags VARCHAR(255)
);

INSERT INTO your_table (id, tags) VALUES
(1, '1,2,3,-52,apple tree,banana fruit'),
(2, '4,5,pear,grape'),
(3, '6,7,8,9,77,88,9878,788,apple,kiwi'),
(4, '10,11,12,orange');
-- Create the view to split the comma-separated tags
CREATE VIEW separated_tags_view AS
WITH RECURSIVE SplitTags AS (
SELECT
id,
SUBSTRING_INDEX(REPLACE(tags, ',', '|'), '|', 1) AS separated_tag,
SUBSTRING(tags, LENGTH(SUBSTRING_INDEX(tags, ',', 1)) + 2) AS remaining_tags
FROM
your_table
WHERE
CHAR_LENGTH(tags) > 0
UNION ALL
SELECT
id,
SUBSTRING_INDEX(REPLACE(remaining_tags, ',', '|'), '|', 1) AS separated_tag,
SUBSTRING(remaining_tags, LENGTH(SUBSTRING_INDEX(remaining_tags, ',', 1)) + 2) AS remaining_tags
FROM
SplitTags
WHERE
CHAR_LENGTH(remaining_tags) > 0
)
SELECT id, separated_tag
FROM SplitTags;
-- Return original table
SELECT * FROM your_table;

-- Query the view
SELECT * FROM separated_tags_view ORDER BY id, separated_tag;`