0

在下面的查詢中,計數發佈的訂閱數量和排序的結果數量。即使計數結果爲0,也會將查詢計數(DISTINCT「reviews」.id)呈現爲my_count

例如:

出版物之一:2條+ 10個註釋= 12(MY_COUNT)

出版物2:2條+ 5個註釋= 7(MY_COUNT)

在殼體上面的查詢可以發現和渲染出版物如預期,但是如果:

公佈三:評論+ 5個=評論5(MY_COUNT)

在這種情況下,查詢將不會呈現發佈三,因爲評論值爲0.即使一個或兩個值都爲0,我怎樣才能使它呈現?所以,基本上我想要在DESC順序中呈現所有記錄,無論值爲0.

感謝您的指導!

@publication = Publication.joins(:reviews, :publication_comments) 
          .select('"publications".*, count(DISTINCT "reviews".id) + count(DISTINCT "publication_comments".id) as my_count') 
          .group('"publications".id') 
          .order("my_count DESC") 

回答

1

您需要使評論和可能的publications_comments表左加入。請試試這個:

@publication = Publication.includes(:reviews, :publication_comments) 
         .select('"publications".*, count(DISTINCT "reviews".id) + count(DISTINCT "publication_comments".id) as my_count') 
         .group('"publications".id') 
         .order("my_count DESC") 
相關問題