gpt4 book ai didi

mysql - 如何设置列值等于另一个表中的值?

转载 作者:搜寻专家 更新时间:2023-10-30 22:16:01 26 4
gpt4 key购买 nike

我想弄清楚如何更新一个表中的行,将列值设置为与另一个表中的值相等。这是一个例子:

movies:

movie_id | movie_price

movies_attended:

attended_id | attended_movie_id | attended_movie_price

现在,这是一个愚蠢的例子,但假设由于某种原因 movies_attended 中有一行没有正确的 attended_movies_price,所以它需要更新。

应该如何编写查询来更新 movies_attended 表,设置 movies_attended.attended_movie_price = movies.movi​​e_price?

我试过类似下面的方法,但没有用:

update movies_attended, movies 
set movies_attended.attended_movie_price = movies.movie_price
where movies_attended.attended_movie_id = movies.movie_id
AND attended_id = [the id of the row we want to update]

最佳答案

当您说“它没有工作”时,您的意思是它报告了 0 行已更新,还是该语句导致数据库引发异常?

您的示例语句似乎是以下形式:

UPDATE movies_attended a
JOIN movies m
ON a.attended_movie_id = m.movie_id
SET a.attended_movie_price = m.movie_price
WHERE a.attended_id = ?

(我们通常更喜欢 JOIN ... ON ... 风格的语法,而不是逗号连接运算符和 WHERE 子句中的连接谓词。)

我无法解释为什么这个声明“不起作用”。

如果没有行满足谓词,这可能会报告 0 行受影响。如果要更改的行不需要任何更改,它还会报告受影响的 0 行...也就是说,attended_movie_price 中的现有值已经与分配给它的值相匹配。

通常,在运行这样的更新语句之前,我先将其写为 SELECT,然后查看返回的值...

通过将 UPDATE 关键字替换为 SELECT ... FROM,并删除 SET 子句:

SELECT m.movie_price          AS new_val
, a.attended_movie_price AS old_val
, a.attended_id
FROM UPDATE movies_attended a
JOIN movies m
ON a.attended_movie_id = m.movie_id
WHERE a.attended_id = ?

关于mysql - 如何设置列值等于另一个表中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12411917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com