mysql - 在 MySQL 中编写一个过程,使用分隔符将列拆分为行

标签 mysql procedure sql-function

这是我的表格:

CREATE TABLE sometbl ( ID INT, NAME VARCHAR(50) );
INSERT INTO sometbl VALUES (1, 'Smith'), (2, 'Julio|Jones|Falcons'), (3,
'White|Snow'), (4, 'Paint|It|Red'), (5, 'Green|Lantern'), (6, 'Brown|bag');

表格输出

----------------------------------------
ID NAME
1 Smith
2 Julio|Jones|Falcons
3 White|Snow
4 Paint|It|Red
5 Green|Lantern
6 Brown|bag
------------------------------------------

输出应该如下所示:

对于 (2),示例行看起来像 >> “3, white”, “3, Snow” ...

请帮助我。

最佳答案

-- sample data = 2 One|Two|Three|Four

-- get the first bit: 2 One
SELECT ID, substring_index(NAME, '|', 1) AS NAME FROM tab

UNION

-- get the 2nd bit: 2 Two
SELECT ID, substring_index(substring_index(NAME, '|', 2),'|',-1) AS NAME FROM tab

UNION

-- get the 3rd bit: 2 Three
SELECT ID, substring_index(substring_index(NAME, '|', 3),'|',-1) AS NAME FROM tab

UNION

-- get the last bit: 2 Four
SELECT ID, substring_index(NAME, '|',-1) AS NAME FROM tab

关于mysql - 在 MySQL 中编写一个过程,使用分隔符将列拆分为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128957/

相关文章:

sql - SQL中如何将单行拆分为多行

php - 文件夹中的图像已删除,但图像路径未在 PHP 中更新为 null

mysql 使用其他表中的数据更新

function - MIPS 中的函数(过程)

c - MIPS:将 C 代码转换为 MIPS 函数调用和返回中的问题

java - JPA:在一个实体上使用多个 @NamedStoredProcedureQuery

java - Mysql更新查询/过程

php - 用户 ID 递增不当

MySQL 插入 ... 选择。在 HAVING 子句中使用 count(column) 而不是 column

返回过去 24 小时内添加的所有行的 MySQL 查询