2015-01-06 18 views
3

我有一個表hstore,有時我用它存儲信息的複選框。 我們使用'1'進行檢查,'0'未使用。沒有爲hstore沒有默認值,以便用戶可以在4個州:軌道查詢hstore其中關鍵是不是東西或不存在

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不存在行?

+0

「@ customers.where(」customers.properties - >'checkbox'LIKE?or customers.properties IS NULL「,」0「)'(不知道這裏的語法) – MrYoshiji

+0

@MrYoshiji謝謝!那讓我成爲那裏的一部分。我認爲我需要尋找空字符串,但我還不太確定 –

+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' 

檢查包含和我做了不就行了找到沒有那些複選框,然後空性。讓我知道它是否有效。

+0

感謝您的回答,但問題是關於特定的hstore密鑰,而不是整個hstore。例如,如果我通常把'{name:「tom」}',那麼我想查詢哪裏的名字是零或不存在。 –

+0

上述評論的任何答案? – Meltemi

相關問題