MySql文本行到列(转置)

时间:2017-08-19 16:45:09

标签: mysql transpose

这里有很多例子可以实现相反的目的 - 列到行。但不是这个。

这些行的网址如下:

颜色:黑色http://www.example.com/1/http://www.example.com/2/http://www.example.com/3/http://www.example.com/4/

我需要将每个网址划分为各个行:

color           URL
color: black    http://www.example.com/1/ 
color: black    http://www.example.com/2/ 
color: black    http://www.example.com/3/
color: black    http://www.example.com/4/

有没有办法在MySql中完成此任务?

1 个答案:

答案 0 :(得分:0)

如果它们位于不同的列中,您可以执行以下操作:

select color, url1 as url from t
union all
select color, url2 from t
union all
select color, url3 from t
union all
select color, url4 from t;

以下可能有效:

如果它们在一个混乱的列中(如示例所示),那么类似于:

select color,
       concat('http:', substring_index(substring_index(concat(url, 'http:'), 'http:', 2), 'http:', -1)) as url
from t
union all
select color,
       concat('http:', substring_index(substring_index(concat(url, 'http:'), 'http:', 3), 'http:', -1)) as url
from t
where url like 'http:%http:%'
union all
select color,
       concat('http:', substring_index(substring_index(concat(url, 'http:'), 'http:', 4), 'http:', -1)) as url
from t
where url like 'http:%http:%http:%';

您将继续为您拥有的每个网址添加子查询。