如何将 SQL 中的信息从一个 table 复制到另一个 table
How to copy information in SQL from one table to another
我需要构建一个查询,将一个列中的信息从一个 table 复制到另一个 table 中的列。
这就是 table 的样子:
人数:
PersonId
Name
StatusId
1
John
2
Jenny
3
Steve
作业:
AssignmentId
Country
PersonId
1
UK.
1
2
USA
3
状态:
StateId
Name
1
Busy
2
Free
People 和 Assignments 之间存在关系 tables:Assignments 上的 PersonId table 是 FK。 People table 通过 FK StatusId 与 Status table 有关系。如果 table 人员中的人员存在于 table 分配中,我需要做的是使用 table 状态中的 StatusId 填充 table 人员的 StatusId。
在上面的示例中,John 和 Steve 都在作业 table 中,在这种情况下,他们在 table 人员中的 StatusId 应设置为 1。
我正在尝试这样做:
update People
set StatusId = 1
where PersonId IN (
select PersonId
from Assignments
where Assignments.PersonId = People.PersonId
)
但是如您所见,我正在对 StatusId 进行硬编码,但这是行不通的。有什么方法可以根据 select 的结果获取 StatusId 吗?还是有其他获取 StatusId 的方法?
如果你想通过“名称”来引用它,你可以使用子查询:
update People
set StatusId = (select s.StatusId from status s where name = 'Busy')
where PersonId IN (select a.PersonId from Assignments a where a.PersonId = People.PersonId);
我需要构建一个查询,将一个列中的信息从一个 table 复制到另一个 table 中的列。
这就是 table 的样子:
人数:
PersonId | Name | StatusId |
---|---|---|
1 | John | |
2 | Jenny | |
3 | Steve |
作业:
AssignmentId | Country | PersonId |
---|---|---|
1 | UK. | 1 |
2 | USA | 3 |
状态:
StateId | Name |
---|---|
1 | Busy |
2 | Free |
People 和 Assignments 之间存在关系 tables:Assignments 上的 PersonId table 是 FK。 People table 通过 FK StatusId 与 Status table 有关系。如果 table 人员中的人员存在于 table 分配中,我需要做的是使用 table 状态中的 StatusId 填充 table 人员的 StatusId。 在上面的示例中,John 和 Steve 都在作业 table 中,在这种情况下,他们在 table 人员中的 StatusId 应设置为 1。
我正在尝试这样做:
update People
set StatusId = 1
where PersonId IN (
select PersonId
from Assignments
where Assignments.PersonId = People.PersonId
)
但是如您所见,我正在对 StatusId 进行硬编码,但这是行不通的。有什么方法可以根据 select 的结果获取 StatusId 吗?还是有其他获取 StatusId 的方法?
如果你想通过“名称”来引用它,你可以使用子查询:
update People
set StatusId = (select s.StatusId from status s where name = 'Busy')
where PersonId IN (select a.PersonId from Assignments a where a.PersonId = People.PersonId);