rails查询hstore,其中key不是或不存在

时间:2015-01-06 18:41:00

标签: sql ruby-on-rails ruby-on-rails-3

我有一个带有hstore的表,有时候我正在使用它来存储复选框的信息。 我们使用'1'表示选中,'0'表示未选中。 hstore没有默认值,因此用户可以处于以下4种状态之一:

customer_a = Customer.new({properties: {checkbox: "1"}})   # checked
customer_b = Customer.new({properties: nil})               # unchecked(object doesn't exist)
customer_c = Customer.new({properties: {checkbox: "0"}})   # unchecked(unchecked)
customer_d = Customer.new({properties: {taco: "chicken"}}) # unchecked(key doesn't exist)

情况:如何查找所有“未选中”的行?

Customer.where(" customer.properties -> 'checkbox' NOT LIKE '1' ")

^^^不起作用^^^忽略空的'复选框'键并且属性为空的客户

Customer.where("customers.properties -> 'checkbox' LIKE '%0%' OR customers.properties IS NULL")

^^^无法正常工作^^^也会忽略密钥丢失的位置

在单个查询中有更好的方法吗?

查询应返回[customer_b, customer_c, customer_d]

目前的解决方案: - 已选中:Customer.where(" customer.properties -> 'checkbox' LIKE '1' ") - 未选中:Customer.all - Customer.where(" customer.properties -> 'checkbox' LIKE '1' ")

是否有sql查询返回不存在hstore密钥的行?

2 个答案:

答案 0 :(得分:2)

如果要查找hstore为空的所有记录,请使用

Customer.where(properties: ['',nil]) 

OR

Customer.where("properties='' OR properties IS NULL")

修改

假设你想要找到关于空字符串的评论中没有1的所有内容,你可以试试吗,

Customer.where("properties -> 'checkbox' NOT LIKE '1' OR NOT(properties ? 'checkbox') OR properties = '' OR properties is null")

检查hstore是否包含密钥

properties ? 'checkbox' 

检查包含,我正在做一个没有找到没有复选框,然后空属性。让我知道它是否有效。

答案 1 :(得分:0)

这将返回复选框键为空或未选中“1”的所有记录

customer = customer.where("properties->'checkbox' != ? OR properties->'checkbox' IS NULL", "1")