【发布时间】:2019-03-28 22:22:56
【问题描述】:
当我进行两个应该选择同一组人的查询时,它们会得到不同的结果。逻辑是一样的,只是数字不同。
这是我的模型:Person class with age:integer name:string pet:string
class Person < ApplicationRecord
PET_TYPES = ['dog', 'cat', 'bird', 'fish']
validates :pet, inclusion: { in: PET_TYPES }, allow_nil: true
validates :age, numericality: { greater_than: 0 }
end
我已经在我的种子文件中填满了数据库中拥有各种宠物(包括零)的人,无论是 21 岁以下还是 21 岁以上:
Person.all.destroy_all
Person::PET_TYPES.each do |pet|
10.times do |n|
Person.create!(name: "Person-young-#{pet}-#{n}", pet: pet, age: (1..20).to_a.sample)
end
10.times do |n|
Person.create!(name: "Person-old-#{pet}-#{n}", pet: pet, age: (21..80).to_a.sample)
end
end
10.times do |n|
Person.create!(name: "Person-young-no-pet-#{n}", pet: nil, age: (1..20).to_a.sample)
end
10.times do |n|
Person.create!(name: "Person-old-no-pet-#{n}", pet: nil, age: (21..80).to_a.sample)
end
我执行了以下两个查询,它们应该选择同一组人。但我得到不同的数字。
Person.count
#>> (1.0ms) SELECT COUNT(*) FROM "people"
#=> 100
Person.where.not(id: Person.where.not('age > ? AND pet = ?', 21, 'dog')).count
#>> (1.7ms) SELECT COUNT(*) FROM "people" WHERE "people"."id" NOT IN (SELECT "people"."id" FROM "people" WHERE NOT (age > 21 AND pet = 'dog'))
#=> 20
Person.where('age > ? AND pet = ?', 21, 'dog').count
#>> (1.0ms) SELECT COUNT(*) FROM "people" WHERE (age > 21 AND pet = 'dog')
#=> 10
这两个语句不应该返回相同的数字吗?
【问题讨论】:
-
您确定得到相同的结果吗?在您的 posgresql 控制台中执行这两个查询。先去掉计数,然后为两个查询选择
age和pet,看看是否得到相同的结果。
标签: sql ruby-on-rails postgresql