简体   繁体   中英

How to count same field twice based on a boolean?

I want to fix my N+1 count problem with a custom select and joins. I have a many-to-many relationship between my posts and tags.Tags can be confirmed or uncofirmed. I want to include the field tags_confirmed_count and tags_unconfirmed_count in my posts select statement (so I can avoid counting tags for each question later).

I have executed counting tags for posts whith the following query:

Post.joins(:tags).select("posts.*, COUNT(tags.id) AS tags_count").group("posts.id")

Now I cannot find a solution to counting tags once for tags that have the field confirmed set to true and once for false.

I tried it this way, but I this way I can only count the confirmed ones, but not the unconfirmed ones:

Post.joins(:tags).select("posts.*, COUNT(tags.id) AS tags_confirmed_count").group("posts.id").where("tags.confirmed = true")

In real SQL not Rails-ish, you'd write:

SELECT 
  count(CASE WHEN confirmed THEN 1 END) AS n_confirmed,
  count(CASE WHEN NOT confirmed THEN 1 END) AS n_unconfirmed,
  ...
FROM posts 
  ...

which will hopefully help you out. No idea how/if that can be translated to ActiveRecord-speak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM