0

I have a table named my_jobs that I am trying to copy a column named "location" into two other columns called "city" and "state." The city and state data need to be extracted in their own respective columns. The city and state columns are already created. The "location" column has multiple different city and state information separated by a comma (Mountain View, CA). I've tried using:

Replace INTO my_jobs (city)
SELECT substring_index(location, ", ",1) 
FROM my_jobs;

But that adds new rows and doesn't merge the data into the existing fields.

asked Feb 2, 2018 at 22:49

1 Answer 1

2

You need to update your table not insert

update my_jobs set city=substring_index(location, ", ",1) ,
state=SUBSTRING(location, LENGTH(location)-2, LENGTH(location))

If you want more explanation add a comment

answered Feb 3, 2018 at 0:32
5
  • 1
    Thanks but I forgot to mention there are multiple different values in the location column, that would replace only one row correct? Commented Feb 3, 2018 at 0:41
  • Sorry, I made a test first and forgotten to change the code :D Commented Feb 3, 2018 at 0:44
  • How would I select the cities if they are varying lengths? Commented Feb 3, 2018 at 1:10
  • What your mean select? I use SUBSTRING, LENGTH and substring_index funcitons to find the size, position and extract the text w3resource.com/mysql/string-functions/mysql-length-function.php techonthenet.com/mysql/functions/substring.php w3schools.com/sql/func_mysql_substring_index.asp Commented Feb 3, 2018 at 1:15
  • 1
    I edited your script to just substring index and that worked for the cities. The issue I was having is that the cities dont have a fixed position like a two character state abbreviation would. I set the substring index to use "comma space" as a delimiter and I didn't have to set a character length. Thanks for your help! Commented Feb 3, 2018 at 7:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.