以下内容作为一个单个字段加载到表中。我意识到这是糟糕的设计,但这是一个我无法控制的过程。我想在此字段中选择多个值作为单独的列。查询,结果和所需结果如下:
查询: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 :(得分: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;
答案 1 :(得分:1)
作为仅使用LOCATE
和SUBSTRING
的替代答案,并且当引号不存在时返回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个主题然后使用另一个答案,它会更清洁:)