"15.2", "quantity"=>"3", "product_id"=>"27", -6ren">
gpt4 book ai didi

sql - 如何使用 hstore 进行 IN 查询?

转载 作者:行者123 更新时间:2023-11-29 13:58:39 24 4
gpt4 key购买 nike

我在包含键和值 (hstore) 的表中有一个字段(内容),如下所示:

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, ....)

提前致谢

最佳答案

取消对 key 的引用并正常使用 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[]
);

但这并不漂亮,而且会慢很多,所以除非万不得已,否则不要这样做。

关于sql - 如何使用 hstore 进行 IN 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26034148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com