Home > Database > Mysql Tutorial > How to Split Comma-Separated Values in SQL into Multiple Rows?

How to Split Comma-Separated Values in SQL into Multiple Rows?

Patricia Arquette
Release: 2025-01-24 04:22:11
Original
132 people have browsed it

How to Split Comma-Separated Values in SQL into Multiple Rows?

Transforming Comma-Separated SQL Values into Multiple Rows

A frequent SQL task involves splitting a single cell's contents into multiple rows. For example, consider this table:

<code class="language-sql">id | name
1  | a,b,c
2  | b</code>
Copy after login

The goal is to restructure this data like so:

<code class="language-sql">id | name
1  | a
1  | b
1  | c
2  | b</code>
Copy after login

Method 1: Leveraging a Numbers Table

One effective solution utilizes a pre-existing "numbers" table (a table containing a sequential list of integers). The query below demonstrates this approach:

<code class="language-sql">SELECT
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) AS name
FROM
  numbers
INNER JOIN
  tablename
ON
  CHAR_LENGTH(tablename.name) - CHAR_LENGTH(REPLACE(tablename.name, ',', '')) >= numbers.n - 1
ORDER BY
  id, n</code>
Copy after login

Method 2: Dynamically Generating Numbers (No Numbers Table Required)

If a dedicated numbers table isn't available, a temporary number sequence can be generated within the query itself:

<code class="language-sql">SELECT
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) AS name
FROM
  (SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5) AS numbers
INNER JOIN
  tablename
ON
  CHAR_LENGTH(tablename.name) - CHAR_LENGTH(REPLACE(tablename.name, ',', '')) >= numbers.n - 1
ORDER BY
  id, n</code>
Copy after login

Remember to adjust the UNION ALL section in the second method to accommodate the maximum number of comma-separated values you anticipate in your name column. Both methods achieve the same outcome—splitting the comma-separated values into individual rows.

The above is the detailed content of How to Split Comma-Separated Values in SQL into Multiple Rows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template