sql - 查找所有关联计数为零和非零的记录
问题描述
class Gallery < ApplicationRecord
has_many :associated_images, as: :imageable
end
class Event < ApplicationRecord
has_many :associated_images, as: :imageable
end
class Image < ApplicationRecord
has_many :associated_images
end
class AssociatedImage < ApplicationRecord
belongs_to :imageable, polymorphic: true
belongs_to :image
end
我想获取所有正在使用的图像,以及一个不同的查询来获取所有未使用的图像(基于AssociatedImage
)。
我试过Image.joins(:associated_images).group('images.id').having('count(image_id) > 0')
了,它返回了正确的结果。但是当我运行时Image.joins(:associated_images).group('images.id').having('count(image_id) = 0')
,它返回一个空#<ActiveRecord::Relation []>
,我不知道为什么会这样。
我的查询基于查找所有关联计数大于零的记录的讨论
解决方案
原因是在 SQL 中,当没有行时计数为零。因此,如果没有行,甚至没有组,就没有结果。
你想要的是
Image.left_joins(:associated_images).where(associated_images: {id: nil}).group('images.id')
当 SQL 进行左连接时,对于没有关联图像的图像,它会为表中的所有列填充 NULL associated_images
。所以那些associated_images.id
是零的,就是我们想要的。
推荐阅读
- r - 如何从内部 git repo 中删除包
- html - 为什么我的 html 按钮先生无法正常工作?
- node.js - 如何在节点 js API 中选择一行并更新 postgresql 表
- python - 当其他两列具有相同的值时,将列值替换为另一列
- ubuntu - 如何使“树”命令变慢?
- flutter - Convert Future
- from Firestore to List
- Flutter Firebase - java - 为什么我无法使用 STS IDE 创建新的 Spring Boot 项目?
- c# - 如何使用 c# asp ionic 库将 zip 文件条目转换为 ZipFile?
- php - PHP SQL 数据库信息未显示
- javascript - Dynamics crm 365快速创建表单获取父实体数据