MySQL UPDATE 记录被另一个表引用

发布于 2025-01-11 10:25:15 字数 1640 浏览 0 评论 0原文

我需要更新其主键被另一个表中的特定列引用的所有记录的特定列。 (外键关系已经建立。) 与我想要做的类似的是:

表 1:三明治

Sandwich(varchar) [Primary Key]Requested(bool)
Salami1
PastramiNull
Ham0
Turkey1

Table 2:Requests

Character(varchar)Sandwich (varchar) [三明治的外键]
CharlieHam
LinusTurkey
MarcyHam
LucySalami
SnoopyPastrami

我希望三明治中的每个空值。请求更新为 1(如果有)是请求中引用其主键的记录。例如,由于 Pastrami 对于三明治.requested 和史努比请求的 Pastrami 具有空值,因此我希望将 Pastrami 的三明治.requested 更新为 1,以便 Sandwiches 看起来如下:

表 1:Sandwiches

Sandwich(varchar) [Primary Key]Requested(bool)
萨拉米1
熏牛肉1
火腿0
火鸡1

我知道如何:

SELECT SANDWICHES.SANDWICH, SANDWICHES.REQUESTED FROM SANDWICHES INNER JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH WHERE REQUESTED = NULL

返回:

三明治请求
熏牛肉Null

告诉我我想要哪些更新,但说我的数据集太大,无法手动执行所有更新。我如何创建更新命令来更新每场比赛?

I need to update a specific column of all records whose primary key is referenced by a specific column in another table. (The foreign key relationship is already set up.)
An analog to what I'm trying to do would be this:

Table 1: Sandwiches

Sandwich(varchar) [Primary Key]Requested(bool)
Salami1
PastramiNull
Ham0
Turkey1

Table 2: Requests

Character(varchar)Sandwich (varchar) [Foreign Key to Sandwiches]
CharlieHam
LinusTurkey
MarcyHam
LucySalami
SnoopyPastrami

I want every null value in sandwiches.requested updated to 1 if there is a record in requests referencing it's primary key. E.g., since Pastrami has a null value for sandwiches.requested and Snoopy requested Pastrami, I want sandwiches.requested updated to 1 for Pastrami, so that Sandwiches looks thus:

Table 1: Sandwiches

Sandwich(varchar) [Primary Key]Requested(bool)
Salami1
Pastrami1
Ham0
Turkey1

I know how to:

SELECT SANDWICHES.SANDWICH, SANDWICHES.REQUESTED FROM SANDWICHES INNER JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH WHERE REQUESTED = NULL

which returns:

SandwichRequested
PastramiNull

telling me which ones I want to update, but say my data set were too large to manually perform all the updates. How would I create an update command to update every match?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

命比纸薄 2025-01-18 10:25:15
Update SANDWICHES JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH set SANDWICHES.REQUESTED = 1 WHERE SANDWICHES.REQUESTED = NULL
Update SANDWICHES JOIN REQUESTS ON SANDWICHES.SANDWICH = REQUESTS.SANDWICH set SANDWICHES.REQUESTED = 1 WHERE SANDWICHES.REQUESTED = NULL
罪歌 2025-01-18 10:25:15

最直接的,就是:

update Sandwiches
set Requested=1
where Sandwich in (select distinct Sandwich from Requests)

Most straightforwardly, just:

update Sandwiches
set Requested=1
where Sandwich in (select distinct Sandwich from Requests)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文