简体   繁体   中英

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. 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)".

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?

We can try using SUBSTRING_INDEX and INSTR here:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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