MySQL将数据分成两个新列

时间:2013-03-05 07:43:09

标签: mysql sql

一列包含数据之间的逗号,我想在我的问题的两个新列中显示这些不同的数据。数据示例,CarAndYear专栏:[Volvo,1995] 我想让'沃尔沃'显示在汽车列和年份'1995'中。我非常感谢这个MySQL问题的帮助。

2 个答案:

答案 0 :(得分:1)

SELECT 
    SUBSTRING_INDEX(TRIM(LEADING '[' FROM `columnname`),',',1) as CARS,
    SUBSTRING_INDEX(TRIM(TRAILING ']' FROM `columnname`),',',-1) as Year 
FROM `tablename`;

SUBSTRING_INDEX in mysql

TRIM in mysql

答案 1 :(得分:1)

假设你总是有前导和尾随括号:

SELECT TRIM(SUBSTR(CarAndYear, 2, INSTR(CarAndYear, ',') - 2)) Cars, 
       TRIM(SUBSTR(CarAndYear, INSTR(CarAndYear, ',') + 1, LENGTH(CarAndYear) - INSTR(CarAndYear, ',') -1)) `Year`
FROM (SELECT '[Volvo, 1995]' CarAndYear) n

输出

+-------+-------+
| Cars  | Year  |
+-------+-------+
| Volvo |  1995 |
+-------+-------+