Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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

share|improve this question
    
Do you want (for every Tracks.prefix) a new row to be inserted or the existing row to be updated? –  ypercube Nov 17 '13 at 11:28
    
yes, every row to be updated –  Raavi Nov 17 '13 at 14:13
add comment

1 Answer

up vote 1 down vote accepted

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 ; 
share|improve this answer
    
Select query you have provided gives me a cross product, there are 7770 rows each in tracks and top 100 tables –  Raavi Nov 17 '13 at 16:35
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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