[英]How to UPDATE using subquery that SELECT's column relative to the parent table?
So, I can't seem to get around this MySQL limitation without changing the entire query or splitting it into a separate SELECT
/ UPDATE
operation pair: 所以,我似乎无法绕过这个MySQL限制而不更改整个查询或将其拆分为单独的
SELECT
/ UPDATE
操作对:
UPDATE `animal`
LEFT JOIN `animalFriends`
ON (`animalFriends`.`animal_id_friend`=`animal`.`id`)
SET `animal`.`trainer_friend_name_latest`=
(
SELECT `trainer`.`name`
FROM `animalFitnessGroup`
LEFT JOIN `trainer`
ON (`animalFitnessGroup`.`trainer_id`=`trainer`.`id`)
WHERE `animalFitnessGroup`.`animal_id_firstMember`=`animal`.`id` OR
`animalFitnessGroup`.`animal_id_firstMember`=`animalFriends`.`animal_id_friend2`
ORDER BY `animalFitnessGroup`.`id` DESC
LIMIT 1
)
WHERE `animal`.`id`=123
This sort of query renders the error: 这种查询呈现错误:
You can't specify target table "animal" for update in FROM clause
您不能在FROM子句中为更新指定目标表“animal”
While I'm sure there's a good reason for this, it's a bit frustrating since the query's intention is clear. 虽然我确信这是有充分理由的,但由于查询的意图很明确,所以有点令人沮丧。 Is there a simple workaround?
有一个简单的解决方法吗? Could
UPDATE FROM
be a solution... without rewriting this into subquery SELECT
operations or two separate operations? 可以
UPDATE FROM
是一个解决方案......而不是将其重写为子查询SELECT
操作或两个单独的操作? https://stackoverflow.com/a/37284940/963901 https://stackoverflow.com/a/37284940/963901
You can try joining all four tables together explicity in the outer UPDATE
statement: 您可以尝试在外部
UPDATE
语句中明确地连接所有四个表:
UPDATE `animal`
LEFT JOIN `animalFriends`
ON (`animalFriends`.`animal_id_friend`=`animal`.`id`)
LEFT JOIN `animalFitnessGroup`
ON `animalFitnessGroup`.`animal_id_firstMember`=`animal`.`id` OR
`animalFitnessGroup`.`animal_id_firstMember`=`animalFriends`.`animal_id_friend2`
LEFT JOIN `trainer`
ON `animalFitnessGroup`.`trainer_id`=`trainer`.`id`
SET `animal`.`trainer_friend_name_latest` = `trainer`.`name`
WHERE `animal`.`id`=123
Without seeing data and having a deeper understanding of the query I cannot be certain that this will behave as you want. 如果没有看到数据并对查询有更深入的了解,我就不能确定这会按照您的意愿行事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.