我有两个表T_SUBJECTS(subject_id,date_of_birth)和T_ADMISSIONS(visit_id,subject_id,date_of_admission,age)。我想用入院时的年龄更新年龄栏。我编写了更新查询并获得"单行子查询返回多行"。我理解错误,但认为where exists子句将解决问题。以下是查询。
UPDATE
t_admissions
SET
t_admissions.age =
(
SELECT
TRUNC(months_between(t_admissions.date_of_admission,
t_subjects.date_of_birth)/12)
FROM
t_admissions,
t_subjects
WHERE
t_admissions.subject_id = t_subjects.subject_id
AND t_admissions.age = 0
AND t_admissions.date_of_admission IS NOT NULL
AND t_subjects.date_of_birth IS NOT NULL
)
WHERE
EXISTS
(
SELECT
1
FROM
t_admissions, t_subjects
WHERE
t_admissions.subject_id = t_subjects.subject_id
);
答案 0 :(得分:1)
问题是SET子句中的子查询返回多行 拥有WHERE子句只会过滤哪些记录得到更新而没有其他内容 此外,您的where子句将始终返回true或始终返回false。
您应该了解如何正确执行相关更新:
https://stackoverflow.com/a/7031405/477563
答案 1 :(得分:1)
根据上述链接的建议,我需要相关更新。见下面的答案。
UPDATE
(
SELECT
t_admissions.visit_id,
t_admissions.date_of_admission doa,
t_admissions.age age,
t_subjects.date_of_birth dob
FROM
t_admissions,
t_subjects
WHERE
t_admissions.subject_id = t_subjects.subject_id
AND t_admissions.age = 0
AND t_admissions.date_of_admission IS NOT NULL
AND t_subjects.date_of_birth IS NOT NULL
)
SET
age = TRUNC(months_between(doa,dob)/12);