向大家求助一个mysql的问题

对于评论的回复,目前流行的主要有两种形式,一种是嵌套评论;另一种是'@评论者'带有悬浮效果。大多博客使用的是嵌套评论,因为嵌套评论更适合较深层次的讨论,我也不例外,前期一直使用嵌套评论。现在换主题了,不想支持嵌套了,取消wordpress的嵌套后,原先有层次的评论就孤立起来而且没有'@评论者',也就是没有悬浮了。

我现在想做的事就是将以前的子评论内容最前面都刷上'@评论者',从而能够通过悬浮效果看到被回复的评论,刷数据的思路很简单,父子评论是通过wp_comments表的comment_parent字段关联的,只要过滤出comment_parent不为空的记录,然后更新comment_content字段就可以了,用习惯了oracle的我以为一个sql可以很轻松的搞定,谁知道mysql居然不支持一下形式的更新嵌套:

[sql]update wp_comments b
set b.comment_content = concat('@',
(select a.comment_author
from wp_comments a
where a.comment_id = b.comment_parent),
'\n',
b.comment_content)
WHERE b.comment_id is not null[/sql]
出错提示为:
#1093 - You can't specify target table 'b' for update in FROM clause

错误提示

查了一下mysql的相关文档,大概就是不允许在子查询同时更新或者删除原数据表数据,知道为什么出错,不过在网上找来一圈,不知道如何依然用一个sql搞定这个功能,只能看着phpMyAdmin发呆了,希望有mysql基础比较扎实的朋友指点迷津,感激不尽,没感激涕零,好人好报,等等等等。

********问题已经解决,以下是自己想出的解决办法

首先拷贝一份评论表的数据到另一张表wp_comments_tmp

[sql]--这个临时表等数据更新后删除就可以了
create table wp_comments_tmp as (select * FROM wp_comments WHERE 1 );[/sql]

然后通过wp_comments表和wp_comments_tmp表的关联,正确SQL如下:

[sql]update wp_comments b
set b.comment_content = concat('',
'@',
(select a.comment_author
from wp_comments_tmp a
where a.comment_id = b.comment_parent),
'
\n',
b.comment_content)
WHERE b.comment_id in
(select comment_id
from (select * from wp_comments where comment_parent != '0') as temp)[/sql]
这个SQL得来也不算容易,最先写好的是下面这样的:
[sql]update wp_comments b
set b.comment_content = concat('',
'@',
(select a.comment_author
from wp_comments_tmp a
where a.comment_id = b.comment_parent),
'
\n',
b.comment_content)
WHERE b.comment_id != '0'[/sql]
这样更新的话,结果是把所有评论内容都被清空了,纠结的一笔,我把update换成select,发现查出的内容果然都是空的,到底是什么原因,我也不太清楚,懂的人解释一下吧。这个sql不行,我就继续改,改成以下形式,用in的形式:
[sql]update wp_comments b
set b.comment_content = concat('',
'@',
(select a.comment_author
from wp_comments_tmp a
where a.comment_id = b.comment_parent),
'
\n',
b.comment_content)
WHERE b.comment_id in
-- 这里又犯了那个错,不能在子查询里更新原表数据
(select comment_id from wp_comments where comment_parent != '0')[/sql]
这个SQL又报1093错误了,最后没辙,继续使用子查询构建临时数据才得到最终可以正确更新的SQL,真是不容易啊,啥时候SQL能强大点啊。

小雪转中雪

2 Comments On 向大家求助一个mysql的问题

  1. avatar

    回访,博主还是技术帝?

| 真的AJAX提交哦

发表评论