sql使用subselect更新多行

时间:2012-06-29 00:24:14

标签: sql sql-update subquery

我正在尝试将gradu_term表中相应的gradu_date值复制到user_education_mba_school表中具有匹配gradu_term_id的行中。这是我的非工作查询

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

- 多连接无法正常工作......

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

4 个答案:

答案 0 :(得分:8)

有几个数据库支持update ... from语法,这很清楚:

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

如果您的数据库没有,请澄清您正在使用的数据库。

答案 1 :(得分:3)

这不起作用,因为您正在设置子查询的整个结果集

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
)

这应该有效(未经测试)

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
)

答案 2 :(得分:0)

UPDATE  mba
SET     graduation_date = gt.graduation_date, mba_graduation_year_id = gt.graduation_year_id
FROM    user_education_mba_school mba
JOIN    [sueldovista].dbo.graduation_term gt
ON      gt.graduation_term_id = mba.graduation_term_id


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    [sueldovista].dbo.graduation_term gt
ON      mba.graduation_term_id = gt.graduation_term_id
JOIN    [sueldovista].dbo.graduation_class gc
ON      gt.graduation_year_id = gc.graduation_year_id
WHERE   gc.site_instance_id = 1

答案 3 :(得分:0)

ORACLE:

更新生产a SET(姓名,计数)=(   SELECT名称,计数   从分段b   WHERE a.ID = b.ID);