Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql update multiple rows with subselect

I am trying to copy the corresponding graduation_date values from the graduation_term table into the rows in the user_education_mba_school table that have the matching graduation_term_id. Here is my nonworking query

TABLE DEFS
**user_education_mba_school
  school_id
  graduation_date
  graduation_term_id

**graduation_term
  graduation_term_id
  graduation_year_id
  graduation_date

**graduation_class
  graduation_class_id
  graduation_year_id  

**user
  user_id
  graduation_class_id

-- Multi-JOIN not working...

UPDATE  u
SET     graduation_class_id = gc.graduation_class_id
FROM    [user] u
JOIN    user_education_mba_school mba
ON      mba.user_id = u.user_id
JOIN    graduation_term gt
ON      mba.graduation_term_id = gt.graduation_term_id
JOIN    graduation_class gc
ON      gt.graduation_year_id = gc.graduation_year_id
like image 342
Adam Levitt Avatar asked Jun 29 '12 00:06

Adam Levitt


2 Answers

Several databases support the update ... from syntax, which is fairly clear:

UPDATE  mba
SET     graduation_date = gt.graduation_date
FROM    user_education_mba_school mba
JOIN    graduation_term gt
ON      gt.graduation_term_id = mba.graduation_term_id

If your database doesn't, please clarify which database you are using.

like image 83
Andomar Avatar answered Oct 18 '22 11:10

Andomar


This isn't going to work because you're setting the entire resultset of the subquery

UPDATE user_education_mba_school SET graduation_date = (
  SELECT gt.graduation_date
  FROM user_education_mba_school mba, graduation_term gt
  WHERE gt.graduation_term_id = mba.graduation_term_id
)

This should work (untested)

UPDATE user_education_mba_school mba SET graduation_date = (
  SELECT gt.graduation_date
  FROM graduation_term gt
  WHERE gt.graduation_term_id = mba.graduation_term_id
)
like image 32
dfb Avatar answered Oct 18 '22 11:10

dfb