Question

I'm a beginner to SQL so this is probably a pretty newbie question, but I can't seem to get my head straight on it. I have a pair of tables called MATCH and SEGMENT.

MATCH.id int(11) ai pk
MATCH.name varchar(45)
etc.

SEGMENT.id int(11) ai pk
SEGMENT.name varchar(45)
etc.

Each row in MATCH can have one or more SEGMENT rows associated with it. The name in MATCH is unique on each row. Right now I do an inner join on the name fields to figure out which segments go with which match. I want to copy the tables to a new set of tables and set up a foreign key in SEGMENT that contains the unique ID from the MATCH row both to improve performance and to fix some problems where the names aren't always precisely the same (and they should be).

Is there a way to do a single INSERT or UPDATE statement that will do the name comparisons and add the foreign key to each row in the SEGMENT table - at least for the rows where the names are precisely the same? (For the ones that don't match, I may have to write a SQL function to "clean" the name by removing extra blanks and special characters before comparing)

Thanks for any help anyone can give me!

Was it helpful?

Solution

Here's one way I would consider doing it: add the FK column, add the constraint definition, then populate the column with an UPDATE statement using a correlated subquery:

ALTER TABLE `SEGMENT` ADD COLUMN match_id INT(11) COMMENT 'FK ref MATCH.id' ;

ALTER TABLE `SEGMENT` ADD CONSTRAINT fk_SEGMENT_MATCH 
  FOREIGN KEY (match_id) REFERENCES `MATCH`(id) ; 

UPDATE `SEGMENT` s
   SET s.match_id = (SELECT m.id
                       FROM MATCH m 
                      WHERE m.name = s.name) ;

A correlated subquery (like in the example UPDATE statement above) usually isn't the most efficient approach to getting a column populated. But it seems a lot of people think it's easier to understand than the (usually) more efficient alternative, an UPDATE using a JOIN operation like this:

UPDATE `SEGMENT` s
  JOIN `MATCH` m
    ON m.name = s.name
   SET s.match_id = m.id

OTHER TIPS

  1. Add an ID field you your MATCH Table and populate it.
  2. them add a column MATCHID (which will be your foriegn key) to your SEGMENT table - Note you wont be able to set this as a Foreign Key till you have mapped the records correctly

Use the following query to update the foreign keys:

UPDATE A
FROM SEGMENT A
INNER JOIn MATCH B
on A.NAME=B.NAME
SET MATCHID = B.ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top