MySQL 是否支持 UPDATE SET FROM 语法?
Is UPDATE SET FROM syntax supported in MySQL?
我们有 table t_post
和 table t_post_like
。
t_post
有一个名为 like_count
的列,用于存储它获得的点赞数。
每次用户喜欢 post,都会在 t_post_like
中创建一个新行,每行包含 post 在列 post_id
中的 ID。 t_post
中的 like_count
字段也将增加 1。
现在我们希望用我在 answer 中找到的 SQL 更正 t_post 中的 like_count
:
update p
set p.like_count = l.like_count_by_post
from t_post p inner join
(
select post_id, count(1) like_count_by_post
from t_post_like
group by post_id
) l
on p.id = l.post_id;
但是我们遇到错误 right syntax to use near 'from t_post c inner join...
,MySQL 是否不支持 update set from
语法?
MySQL 确实支持更新连接语法,但它看起来更像这样:
UPDATE t_post p
INNER JOIN
(
SELECT post_id, COUNT(*) like_count_by_post
FROM t_post_like
GROUP BY post_id
) l
ON l.post_id = p.id
SET
like_count = l.like_count_by_post;
我们有 table t_post
和 table t_post_like
。
t_post
有一个名为 like_count
的列,用于存储它获得的点赞数。
每次用户喜欢 post,都会在 t_post_like
中创建一个新行,每行包含 post 在列 post_id
中的 ID。 t_post
中的 like_count
字段也将增加 1。
现在我们希望用我在 answer 中找到的 SQL 更正 t_post 中的 like_count
:
update p
set p.like_count = l.like_count_by_post
from t_post p inner join
(
select post_id, count(1) like_count_by_post
from t_post_like
group by post_id
) l
on p.id = l.post_id;
但是我们遇到错误 right syntax to use near 'from t_post c inner join...
,MySQL 是否不支持 update set from
语法?
MySQL 确实支持更新连接语法,但它看起来更像这样:
UPDATE t_post p
INNER JOIN
(
SELECT post_id, COUNT(*) like_count_by_post
FROM t_post_like
GROUP BY post_id
) l
ON l.post_id = p.id
SET
like_count = l.like_count_by_post;