我在这里找到了一个很好的资源( Comparing two bitmasks in SQL to see if any of the bits match ),用于在SQL数据库中进行搜索,您可以使用位掩码存储具有多个属性的数据。不过,在本例中,所有数据都存储为int类型,where子句似乎只适用于int类型。
有没有一种简单的方法可以将非常相似的测试用例转换为使用完整的位串?因此,不是像这样的例子:
with test (id, username, roles)
AS
(
SELECT 1,'Dave',1
UNION SELECT 2,'Charlie',3
UNION SELECT 3,'Susan',5
UNION SELECT 4,'Nick',2
)
select * from test where (roles & 7) != 0 取而代之的是这样的东西:
with test (id, username, roles)
AS
(
SELECT 1,'Dave',B'001'
UNION SELECT 2,'Charlie',B'011'
UNION SELECT 3,'Susan',B'101'
UNION SELECT 4,'Nick',B'110'
)
select * from test where (roles & B'001') != 0 我可以来回转换,但用实际的位串更容易可视化。对于我的简单转换(如上),我得到了一个错误,运算符不适用于位串。有没有另一种方法可以设置它呢?
发布于 2013-01-08 05:25:21
一种方法是在表达式的右侧也使用bit string:
WITH test (id, username, roles) AS (
VALUES
(1,'Dave',B'001')
,(2,'Charlie',B'011')
,(3,'Susan',B'101')
,(4,'Nick',B'110')
)
SELECT *, (roles & B'001') AS intersection
FROM test
WHERE (roles & B'001') <> B'000';或者,您可以将integer 0转换为bit(3)
...
WHERE (roles & B'001') <> 0::bit(3);您可能会对此相关答案感兴趣,该答案演示了在boolean、bit string和integer之间进行转换的多种方法
Can I convert a bunch of boolean columns to a single bitmap in PostgreSQL?
请注意,将数据存储为integer可以节省一些空间。integer需要4字节来存储最多32位的信息,而-I引用manual at said location
位字符串值要求为每组8位使用1字节,加上5或8字节开销,具体取决于字符串的长度...
https://stackoverflow.com/questions/14200486
复制相似问题