2014-10-30 33 views
1

我认为这将是一个简单的查询,但它比我想象的要困难。跳过次数用户评论

我有一个简单的论坛应用程序,用户打开一个故事,然后其他用户可以发表评论。

两个表是

故事

id 
user_id 
subject 
approved 

评论

id 
user_id 
story_id 
approved 

基本上,我想通过不计算楼主自己的评论来查询悬而未决的故事。即使其他人发布了新评论,但在评论尚未获得批准时,也不应该将其视为回复故事。

select * from stories left join comments on stories.id = comments.story_id 
having count(comments.id) = 0 or (count(comments.id) > 0 and comments.user_id = stories.user_id) 

它工作正常,没有'approved'标志,但我不能让它工作,当我添加'批准'到where/having子句。

我在做什么错?

回答

1

我移动count为子查询,并把在in条件来检查什么的回答,什么是不:

SELECT s.* 
FROM stories s 
WHERE s.id NOT IN (SELECT story_id 
        FROM  comments c 
        WHERE approved = true AND 
          c.user_id != s.user_id 
        GROUP BY story_id 
        HAVING COUNT(*) > 0) 
+0

谢谢@Mureinik!这似乎工作。只是一个新手问题......它应该比加入+有慢吗? – Moon 2014-10-30 06:29:05

+0

@Moon它**不应该是,但如果没有在你的实际数据集上分析它,这真的很难回答。 – Mureinik 2014-10-30 06:30:19

+0

//谢谢!我将在有限的知识范围内进行分析。 – Moon 2014-10-30 06:32:13

1

试试这个未经测试的查询:

select * 
from stories 
    left join comments on stories.id = comments.story_id and comments.user_id <> stories.user_id 
having count(comments.id) = 0 
+0

谢谢@延斯,但它不起作用。我什么都没有回来。 – Moon 2014-10-30 06:24:47