[英]return 0 if null count
source: has_many comments来源:has_many评论
comments: has_many training_comments评论:has_many training_comments
@negative_comments = Source.joins(:comments => [:training_comments]).where("training_comments.category_id = ? and comments.spam = ?", 2, false).select("sources.*, count(comments.id) as ncount").group("comments.source_id")
I want to list sources with their negative comments count but i am loosing sources which don't have negative_comments(training_entries.category_id = 2).我想列出带有负面评论计数的来源,但我正在失去没有负面评论(training_entries.category_id = 2)的来源。 I tried everything to achieve this.我尝试了一切来实现这一目标。 I tried left join, i tried ifnull but none of them worked.我尝试了左连接,我尝试了 ifnull 但它们都没有工作。 Any help will be really really appreciated..任何帮助都会非常感激..
What i'm trying to do我想要做什么
Sources Count来源计数
source1 5来源1 5
source2 0源2 0
source3 13来源3 13
what i'm getting is我得到的是
Sources Count来源计数
source1 5来源1 5
source3 13来源3 13
Sources table来源表
id: integer
name: string
Comments table评论表
id: integer
source_id: integer
spam: boolean
Training_comments table Training_comments 表
id: integer
comment_id: integer
category_id: integer
You're getting a zero because the standard JOIN doesn't produce anything when there is no match.你得到一个零,因为标准 JOIN 在没有匹配时不会产生任何东西。 You need to get a LEFT OUTER JOIN past ActiveRecord;您需要通过 ActiveRecord 获得LEFT OUTER JOIN ; something like this:像这样的东西:
joins('LEFT OUTER JOIN comments ON comments.source_id = sources.id')
AFAIK, you have to drop down to SQL to get a LEFT OUTER JOIN. AFAIK,您必须下拉到 SQL 才能获得 LEFT OUTER JOIN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.