问题描述:
增加一个文章置顶功能,使用一个字段(初始为零)来表示文章的优先级,
每次置顶让对应文章的该字段+1
于是有了这样一段sql
<!--文章置顶-->
<update id="updateBlogTop">
update blog
set top = (select max(top) from blog where author_id = #{authorId}) + 1
where id = #{articleId}
</update>
后发现执行时提示错误
You can’t specify target table
原因:Mysql的不支持先select再update同一个表。
解决方案:可以将数据取出来当作一个临时表,再在临时表中查询Max(top)
修改后的sql
<!--文章置顶-->
<update id="updateBlogTop">
update blog
set top = (select max(top) from (select * from blog where author_id = #{authorId}) as `b*`) + 1
where id = #{articleId}
</update>