简体   繁体   English

MySQL - 从子查询更新列

[英]MySQL - updating column from a subquery

Can't get this to work. 无法让这个工作。 I have a table 'Players' which has a primary key 'Id' and among others, a 'Name' column. 我有一个'玩家'表,其中有一个主键'Id',还有一个'Name'列。 Another table 'Bookings' has a column 'PlayerId' which references 'Players.Id'. 另一个表'预订'有一个列'PlayerId',它引用了'Players.Id'。

I have just added a column 'Name' to 'Bookings' which needs to contain an actual copy of the player's name. 我刚刚在“预订”中添加了一个“名称”列,其中需要包含玩家姓名的实际副本。

I am trying set fill in all the names in Bookings using the following statement: 我正在尝试使用以下语句设置填充预订中的所有名称:

UPDATE Bookings SET Name = (SELECT Name FROM Players WHERE Players.Id=Bookings.PlayerId);

but what I get is error 1263: "Column set to default value; NULL supplied to NOT NULL column 'Name' at row 0". 但我得到的是错误1263:“列设置为默认值; NULL提供给NOT NULL列'名称'在第0行”。

What have I done wrong? 我做错了什么?

Try this: 尝试这个:

update Bookings, Players
set Bookings.Name = Players.Name
where Bookings.playerId = Players.Id

You have to be sure that there's a one to one relation between Players and Bookings (it's the only way I think this makes any sense). 你必须确保PlayersBookings之间存在一对一的关系(这是我觉得这没有任何意义的唯一方式)。

Use MYSQL UPDATE JOIN for this purpose. 为此,请使用MYSQL UPDATE JOIN。 This is the query you need: 这是您需要的查询:

UPDATE Bookings
LEFT JOIN Players
ON Players.Id=Bookings.PlayerId
SET Bookings.Name = Players.Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM