2014-09-25 101 views
1

我有在表中含有這樣的鍵和值(hstore)的字段(內容):如何使用hstore進行IN查詢?

content: {"price"=>"15.2", "quantity"=>"3", "product_id"=>"27", "category_id"=>"2", "manufacturer_id"=>"D"} 

我可以具有一個CATEGORY_ID容易地選擇產物與:

SELECT * FROM table WHERE "content @> 'category_id=>27'" 

我想選擇所有行都有(例如)category_id在值列表中。

在傳統的SQL它會是這樣的:

SELECT * FROM TABLE WHERE category_id IN (27, 28, 29, ....) 

感謝您提前

回答

2

去參考的關鍵,並與IN正常測試。

CREATE TABLE hstoredemo(content hstore not null); 

INSERT INTO hstoredemo(content) VALUES 
('"price"=>"15.2", "quantity"=>"3", "product_id"=>"27", "category_id"=>"2", "manufacturer_id"=>"D"'); 

然後是其中之一。第一個更清晰,因爲它將提取的值轉換爲整數,而不是對數字進行字符串比較。

SELECT * 
FROM hstoredemo 
WHERE (content -> 'category_id')::integer IN (2, 27, 28, 29); 

SELECT * 
FROM hstoredemo 
WHERE content -> 'category_id' IN ('2', '27', '28', '29'); 

如果你要測試更復雜的hstore包含操作,說有多個按鍵,你可以使用@> ANY,例如

SELECT * 
FROM hstoredemo 
WHERE 
    content @> ANY(
    ARRAY[ 
     '"category_id"=>"27","product_id"=>"27"', 
     '"category_id"=>"2","product_id"=>"27"' 
    ]::hstore[] 
); 

,但它不是漂亮,而且這將是一個慢了很多,所以,除非你有沒有做到這一點。

+0

非常感謝:-) – Sucrenoir 2014-09-26 05:56:05

+0

@Sucrenoir感謝*你*爲顯示所需的SQL和數據,使它成爲一個快速簡單的答案,無需來回。 – 2014-09-26 05:58:17

-2
category_ids = ["27", "28", "29"] 
Tablename.where("category_id IN(?)", category_ids) 
相關問題