简体   繁体   English

有没有一种方法可以将列中的2个值分成两个独立的列?

[英]Is there a way to seperate 2 values in column into two seperate columns?

The problem is to sort the movies by movie Id and to split the title and year into separate columns in MySQL. 问题是按电影ID对电影进行排序,并将标题和年份拆分为MySQL中的单独列。 Sorting the movies is not an issue but I am trying to separate a column with two sets of data in it. 对电影进行排序不是问题,但是我试图将其中包含两组数据的列分开。 One being the movie title and the other being the year that the movie was released. 一个是电影的标题,另一个是电影的发行年份。

Examples being "Toy Story (1998)", "Iron Giant (1999)". 例如“玩具总动员(1998)”,“铁巨人(1999)”。

The desired output would be to have a title column and a corresponding year column for these movies. 期望的输出将是这些电影具有标题列和相应的年份列。

There are about an upwards of a million columns that I would have to split the movie title and the year for. 我将不得不拆分大约一百万列电影标题和年份。 Is there anyway to this is MySQL? 反正是MySQL吗?

We can try using SUBSTRING_INDEX and INSTR here: 我们可以在这里尝试使用SUBSTRING_INDEXINSTR

SELECT
    SUBSTRING(title, 1, INSTR(title, '(') - 2) AS name,
    REPLACE(REPLACE(SUBSTRING_INDEX(title, ' ', -1), '(', ''), ')', '') AS year
FROM yourTable;

在此处输入图片说明

Demo 演示

We isolate the name of the movie by taking a substring up to, but not including, the first space and opening parenthesis. 我们通过使用一个子字符串来分隔电影的名称,该子字符串最多但不包括第一个空格和左括号。 The year is found by taking the final term and removing opening and closing parentheses. 可以通过采用最后一项并删除左括号和右括号来找到年份。

I would just use substring_index() for this: 我将为此使用substring_index()

select substring_index(titleyear, ' (', 1) as title,
       substring_index(titleyear, ' (', -1) + 0 as year

The second piece uses implicit conversion to store the value as a year. 第二部分使用隐式转换将值存储为一年。

You can also extract the year as a string using: 您还可以使用以下方式将年份提取为字符串:

substr(titleyear, -5, 4) as year

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM