0

There are 3 tables:

  1. Label (Label_ID,Label_Name), Label_ID is Primary Key.
  2. Tracks (Prefix, Label_ID), Prefix is Primary Key,Label_ID is empty column
  3. Top100 (Prefix,Label) No keys in this table.

My query should be such that , For each prefix row in Tracks table, find an equivalent prefix in top100 table then select Label from top100 table, Match thus selected Label with Label_name in Label table, get its Label_ID and Update its value in Tracks table.

Can anyone please help me with this query?? Any help much appreciated

2
  • Do you want (for every Tracks.prefix) a new row to be inserted or the existing row to be updated? Nov 17, 2013 at 11:28
  • yes, every row to be updated Nov 17, 2013 at 14:13

1 Answer 1

1

I guess you don't want (for every Tracks.prefix) a new row to be inserted but the existing row to be updated (otherwise you would get collisions on the primary key of Tracks). You can this query to check first what will be changed:

SELECT 
    tr.prefix,
    tr.label_id AS existing_label_id,
    top.label,
    lbl.label_id AS new_label_id 
FROM 
    Tracks AS tr
  JOIN
    Top100 AS top  ON top.prefix = tr.prefix
  JOIN
    Label AS lbl  ON lbl.label_name = top.label ;

and then update:

UPDATE
    Tracks AS tr
  JOIN
    Top100 AS top  ON top.prefix = tr.prefix
  JOIN
    Label AS lbl  ON lbl.label_name = top.label
SET
    tr.label_id = lbl.label_id ; 
1
  • Select query you have provided gives me a cross product, there are 7770 rows each in tracks and top 100 tables Nov 17, 2013 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.