Oracle Update Query - 单行子查询返回多行

时间:2017-03-07 15:16:46

标签: sql oracle

我试图运行以下查询 -

SELECT s.forename,
  hss.forename,
  s.surname,
  hss.surname,
  s.dob,
  s.ethnic_or,
  hss.ethnicity,
  s.person_id,
  hs.term_id,
  hs.status_text
FROM people s
INNER JOIN headcount_submission_student hss
ON hss.import_stud_id = s.person_id
INNER JOIN headcount_submission hs
ON hs.submission_student_id = hss.submission_student_id
WHERE s.ethnic_or          IS NULL
AND NOT hss.ethnicity      IS NULL
AND hs.term_id             = 48
GROUP BY s.forename,
  hss.forename,
  s.surname,
  hss.surname,
  s.dob,
  s.ethnic_or,
  hss.ethnicity,
  s.person_id,
  hs.term_id,
  hs.status_text
ORDER BY s.surname;

作为UPDATE查询,因为我想使用hss.ethnicity中的值更新s.ethnic_or列中的所有值

我尝试了各种不同的方式,但到目前为止还没有快乐。有谁能提出建议?

我一直在

  

SQL错误:ORA-01427:单行子查询返回多行

尝试此时

UPDATE People t1
SET
  (
    t1.ethnic_or
  )
  =
  (SELECT hss.ethnicity
  FROM headcount_submission_student hss
  INNER JOIN headcount_submission hs
  ON hs.submission_student_id = hss.submission_student_id
  WHERE NOT hss.ethnicity    IS NULL
  AND term_id                 = 48
  AND NOT hss.import_stud_id IN (136791, 140481, 140490, 140582)
  )
WHERE EXISTS
  (SELECT NULL
  FROM headcount_submission_student hss
  INNER JOIN headcount_submission hs
  ON hs.submission_student_id = hss.submission_student_id
  WHERE NOT hss.ethnicity    IS NULL
  AND hs.term_id                 = 48
  AND hss.import_stud_id      = t1.person_id
  )
AND t1.ethnic_or IS NULL;

1 个答案:

答案 0 :(得分:0)

首先提示,不要将表“t1”别名,使用有意义的别名。在你的情况下,表是人,不要别名或使用像“ppl”这样的东西。您的SQL将更容易阅读。

现在,我采取了一些自由,而不是解决返回多行的子查询,我使用子查询重写了以下更新。在子查询中,我试图复制您的连接和过滤器,以使人们错过种族,但在其他表格中填充了哪些内容。看看这个替代方案。

update
(select people.ethnic_or, hss.ethnicity
from   people
inner join headcount_submission_student hss on (people.person_id = hss.import_stud_id)
inner join head_count_submission hs on (hs.submission_student_id = hss.submission_student_id and hs.term_id = 48)
where people.ethnic_or IS NULL
  AND hss.ethnicity IS NOT NULL
  and hss.import_stud_id NOT IN (136791, 140481, 140490, 140582))
set   ethnic_or = ethnicity;