简体   繁体   中英

SQL - values from one table column to another table column

I have two tables

songs (id, name, artist, artist_id)    
artist (id, name)    

What i am trying to do is take the id values from artist and put that value into the value of artist_id in the songs table

The values of artist_id in songs is currently NOT NULL and has no value at the moment

ARTIST table

id    |     name    
1     |     name1    
2     |     name2    
etc

SONGS table

id   | name   | artist  | artist_id    
id1  | name1  | artist1 | NOT NULL    
id2  | name2  | artist2 | NOT NULL    
id3  | name3  | artist3 | NOT NULL    
id4  | name4  | artist4 | NOT NULL    

I need it to be an UPDATE statement using subqueries and this is what I have. I do not have any errors.

The issue is that artist_id is being filled with 0's instead of the actual corresponding value of id from the artist table.

UPDATE songs 
  JOIN artist 
    ON artist.id = songs.artist_id 
   SET songs.artist_id = artist.id;

the subquery goes through the MySQL terminal but doesn't tranfer values over, instead just gives me 0's

UPDATE songs
  JOIN artist 
    ON songs.artist_id = artist.id
   SET songs.artist_id = artist.id;

I even tried to alter it a bit and it still displays a 0 instead of the corresponding value.

The only way to relate the 2 tables is with the artist's name:

UPDATE songs s
INNER JOIN artist a 
ON s.artist = a.name
SET s.artist_id = a.id; 

If this UPDATE statement succeeds then you should delete the column artist from songs and keep only the column artist_id .

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