2013-12-20 22 views
-1

以下内容作为一个单一字段加载到表中。我意识到这是糟糕的设计,但这是一个失控的过程。我想在此字段中选择多个值作为单独的列。查询,结果和期望的结果如下:MySQL - 在列中的字符之间选择多个值作为单独的列

查询:Select theme from table1;

结果:

"different LTs" is neutral (sentiment score: 0.245, relevancy: 4) "following LTs" is neutral (sentiment score: 0.245, relevancy: 4) "common lieutenants" is neutral (sentiment score: 0.245, relevancy: 4) 

期望的结果(如3个独立的列):

theme1   | theme2  | theme3 

different LTs | following LTs | common lieutenants 

我如何实现这在SQL中?先谢谢您的帮助!

+0

你必须使用大量locate'的'和'substr'电话提取字符串的每个部分。如果您执行一些搜索,则可以找到可用于使其更容易的正则表达式UDF。 – Barmar

回答

1

作为替代答案只能用LOCATESUBSTRING,并在报价中不存在(例如像,如果返回null你只有theme1和theme2,或者如果你只有theme1,或者你没有任何主题)。你可以试试这个疯狂的一个(sqlFiddle

SELECT theme, 
    SUBSTRING(theme,IF(LOCATE('"',theme)=0,NULL,LOCATE('"',theme))+1, 
        IF(LOCATE('"',theme,LOCATE('"',theme)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme)+1))- 
        IF(LOCATE('"',theme)=0,NULL,LOCATE('"',theme))-1) as theme1, 
    SUBSTRING(theme,IF(LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1))+1, 
        IF(LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1))- 
        IF(LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1))-1) as theme2, 
    SUBSTRING(theme,IF(LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)+1))+1, 
        IF(LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)+1)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)+1)+1))- 
        IF(LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)+1)=0,NULL,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme,LOCATE('"',theme)+1)+1)+1)+1))-1) as theme3 
FROM table1 

,如果你总是有3个主题,然后使用对方的回答,这是干净多了:)

+0

很棒!我确实有一些行,总主题并不总是3,有2个,有时候是1个。所以这个效果很好。欣赏它。 – karthicks

3

如果所有值都具有相同的形式,那么你可以使用此查询 -

SELECT 
    SUBSTRING_INDEX(SUBSTRING_INDEX(theme, '"', 2), '"', -1) theme1, 
    SUBSTRING_INDEX(SUBSTRING_INDEX(theme, '"', 4), '"', -1) theme2, 
    SUBSTRING_INDEX(SUBSTRING_INDEX(theme, '"', 6), '"', -1) theme3 
FROM 
    table1; 
+0

实际上有三个主题时,此功能非常有用,但当有一个,两个和三个不可用时,它会将主题1后面的字符选为2和3。例如: Theme1 |主题2 |主题3 论坛用户| \t为正值(情感评分:0.600,相关度:4)| \t是正面的(情感得分:0.600,相关度:4) – karthicks

+0

@karthicks是的,这个查询是非常具体的。 – Devart