帮助MySQL子查询

时间:2011-03-25 05:05:53

标签: mysql

基本上我所拥有的是MySQL表的注释。我有一个名为'parent_id'的列,用于跟踪评论是否是对另一个评论的回复。

我想要做的就是计算所有评论。这工作正常,但是如果您删除评论而不是回复,则会将其视为仍处于活动状态,但保持不变。

这是我目前无法正常工作的MySQL查询......有什么想法吗?

SELECT ic.* 
FROM roster_services_items_comments AS ic 
WHERE (SELECT icp.id FROM roster_services_items_comments AS icp 
       WHERE ic.parent_id = '' 
       OR (icp.id = ic.parent_id AND icp.deleted != 0) 
       LIMIT 1) IS NOT NULL

3 个答案:

答案 0 :(得分:1)

怎么样:

SELECT ic.*, COUNT(icp.parent_id) AS replies_count
FROM roster_services_items_comments AS ic
LEFT JOIN roster_services_items_comments AS icp ON ic.id = icp.parent_id
WHERE ic.deleted != 0
GROUP BY ic.id
HAVING ic.parent_id IS NULL

编辑:修正了如果评论没有任何回复则计数不计算

答案 1 :(得分:0)

您应该添加一个触发器,用于标记要删除的已删除的回复

问题是您需要递归检查可能的父母和父母的父母的当前评论

你可以创建一个递归函数,它确定它是否删除了父母

答案 2 :(得分:0)

Select Count(*)
From roster_services_items_comments As ic 
Where ( ic.parent_id = '' And deleted = 0 )
    Or ic.id Not In (
                    Select ic1.parent_id
                    From roster_services_items_comments As ic1
                    Where ic1.deleted = 1
                    )

parent_id真的可以是一个空字符串吗?当parent_id成为最高评论时,它是否更有意义为NULL?如果这是真的,我们有:

Select Count(*)
From roster_services_items_comments As ic 
Where ( ic.parent_id Is Null And deleted = 0 )
    Or ic.id Not In (
                    Select ic1.parent_id
                    From roster_services_items_comments As ic1
                    Where ic1.deleted = 1
                    )