SQL 中两个表之间的条件更新
Conditional update between two tables in SQL
下面两张表,对于同校名的学生和家长:我想让它把parent_name赋值给student_name。
CREATE TABLE students2 (
student_id CHAR(2),
student_name VARCHAR2(30),
student_grade NUMBER(2),
school_name VARCHAR2(50)
)
CREATE TABLE parents (
student_id CHAR(2),
parent_name VARCHAR2(30),
school_name VARCHAR2(50)
)
UPDATE students2
SET student_name = (SELECT parent_name
FROM parents
WHERE parents.school_name = students2.school_name)
当我写这个查询时,更新完成了,但是 student_name 不满足条件的 NULL
。他们不应该改变。
您需要说明应该更新哪些行;参见 WHERE EXISTS
。
UPDATE students2 a SET
a.student_name = (SELECT b.parent_name
FROM parents b
WHERE b.school_name = a.school_name)
WHERE EXISTS (SELECT NULL
FROM parents c
WHERE c.school_name = a.school_name);
或者,由于您还没有学习 EXISTS
:
UPDATE students2 a SET
a.student_name = (SELECT b.parent_name
FROM parents b
WHERE b.school_name = a.school_name)
WHERE a.school_name IN (select c.school_name
FROM parents c);
据我了解,如果要将 parent_name 分配给 student_name,查询不应该是这样的-
UPDATE students2 SET student_name = (SELECT parent_name FROM parents WHERE parents.student_id= students2.student_id)
无论如何,如果我遗漏了什么或者你已经知道了,也许你可以试试这个空值:
UPDATE students2 SET student_name =(SELECT parent_name FROM parents
WHERE
CASE
WHEN %s IS NOT NULL
< statements >
ELSE < statements >
END
[AND/OR] <other constraints here> )
如有错误请指正
下面两张表,对于同校名的学生和家长:我想让它把parent_name赋值给student_name。
CREATE TABLE students2 (
student_id CHAR(2),
student_name VARCHAR2(30),
student_grade NUMBER(2),
school_name VARCHAR2(50)
)
CREATE TABLE parents (
student_id CHAR(2),
parent_name VARCHAR2(30),
school_name VARCHAR2(50)
)
UPDATE students2
SET student_name = (SELECT parent_name
FROM parents
WHERE parents.school_name = students2.school_name)
当我写这个查询时,更新完成了,但是 student_name 不满足条件的 NULL
。他们不应该改变。
您需要说明应该更新哪些行;参见 WHERE EXISTS
。
UPDATE students2 a SET
a.student_name = (SELECT b.parent_name
FROM parents b
WHERE b.school_name = a.school_name)
WHERE EXISTS (SELECT NULL
FROM parents c
WHERE c.school_name = a.school_name);
或者,由于您还没有学习 EXISTS
:
UPDATE students2 a SET
a.student_name = (SELECT b.parent_name
FROM parents b
WHERE b.school_name = a.school_name)
WHERE a.school_name IN (select c.school_name
FROM parents c);
据我了解,如果要将 parent_name 分配给 student_name,查询不应该是这样的-
UPDATE students2 SET student_name = (SELECT parent_name FROM parents WHERE parents.student_id= students2.student_id)
无论如何,如果我遗漏了什么或者你已经知道了,也许你可以试试这个空值:
UPDATE students2 SET student_name =(SELECT parent_name FROM parents
WHERE
CASE
WHEN %s IS NOT NULL
< statements >
ELSE < statements >
END
[AND/OR] <other constraints here> )
如有错误请指正