MySQL 更新另一个 table 引用的记录
MySQL UPDATE records referenced by another table
我需要更新所有记录的特定列,其主键被另一个 table 中的特定列引用。 (外键关系已经建立。)
类似于我正在尝试做的事情是这样的:
Table 1: 三明治
Sandwich(varchar) [Primary Key]
Requested(bool)
Salami
1
Pastrami
Null
Ham
0
Turkey
1
Table 2:请求
Character(varchar)
Sandwich (varchar) [Foreign Key to Sandwiches]
Charlie
Ham
Linus
Turkey
Marcy
Ham
Lucy
Salami
Snoopy
Pastrami
如果请求中有记录引用它的主键,我希望 sandwiches.requested 中的每个空值都更新为 1。例如,由于 Pastrami 的 sandwiches.requested 为空值,而 Snoopy 请求了 Pastrami,我希望将 sandwiches.requested 更新为 1 来表示 Pastrami,这样三明治看起来是这样的:
Table 1: 三明治
Sandwich(varchar) [Primary Key]
Requested(bool)
Salami
1
Pastrami
1
Ham
0
Turkey
1
我知道如何:
SELECT SANDWICHES.SANDWICH, SANDWICHES.REQUESTED FROM SANDWICHES INNER JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH WHERE REQUESTED = NULL
哪个returns:
Sandwich
Requested
Pastrami
Null
告诉我要更新哪些,但说我的数据集太大而无法手动执行所有更新。我将如何创建更新命令来更新每场比赛?
最直接的,就是:
update Sandwiches
set Requested=1
where Sandwich in (select distinct Sandwich from Requests)
Update SANDWICHES JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH set SANDWICHES.REQUESTED = 1 WHERE SANDWICHES.REQUESTED = NULL
我需要更新所有记录的特定列,其主键被另一个 table 中的特定列引用。 (外键关系已经建立。) 类似于我正在尝试做的事情是这样的:
Table 1: 三明治
Sandwich(varchar) [Primary Key] | Requested(bool) |
---|---|
Salami | 1 |
Pastrami | Null |
Ham | 0 |
Turkey | 1 |
Table 2:请求
Character(varchar) | Sandwich (varchar) [Foreign Key to Sandwiches] |
---|---|
Charlie | Ham |
Linus | Turkey |
Marcy | Ham |
Lucy | Salami |
Snoopy | Pastrami |
如果请求中有记录引用它的主键,我希望 sandwiches.requested 中的每个空值都更新为 1。例如,由于 Pastrami 的 sandwiches.requested 为空值,而 Snoopy 请求了 Pastrami,我希望将 sandwiches.requested 更新为 1 来表示 Pastrami,这样三明治看起来是这样的:
Table 1: 三明治
Sandwich(varchar) [Primary Key] | Requested(bool) |
---|---|
Salami | 1 |
Pastrami | 1 |
Ham | 0 |
Turkey | 1 |
我知道如何:
SELECT SANDWICHES.SANDWICH, SANDWICHES.REQUESTED FROM SANDWICHES INNER JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH WHERE REQUESTED = NULL
哪个returns:
Sandwich | Requested |
---|---|
Pastrami | Null |
告诉我要更新哪些,但说我的数据集太大而无法手动执行所有更新。我将如何创建更新命令来更新每场比赛?
最直接的,就是:
update Sandwiches
set Requested=1
where Sandwich in (select distinct Sandwich from Requests)
Update SANDWICHES JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH set SANDWICHES.REQUESTED = 1 WHERE SANDWICHES.REQUESTED = NULL