你会如何查询一系列1和0的字符从一个数据库?
题
说你有一长列文字是1或0,有点像一个bitvector,但在一个数据库列。你会如何查询知道什么值设定/没有设置?说你需要知道如果char500和char1500是"真实"或没有。
解决方案
SELECT
Id
FROM
BitVectorTable
WHERE
SUBSTRING(BitVector, 500, 1) = '1'
AND SUBSTRING(BitVector, 1000, 1) = '1'
没有索引可以使用这种类型的查询,虽然。当你有很多行,这将得到缓慢的速度非常快。
编辑:就SQL服务器至少,所有内置串职能 的确定性.这意味着你可以看看能否使用计算的列基于SUBSTRING()的结果为整个组合的价值, 把索引他们每个人.插入将缓慢,表格的尺寸将增加,但是搜索将很快。
SELECT
Id
FROM
BitVectorTable
WHERE
BitVector_0500 = '1'
AND BitVector_1000 = '1'
编辑#2:的 限制SQL服务器 有:
- 1024个列每正常表
- 30.000的列每个"广泛"的表
其他提示
在MySQL中,一些使用子一>像
select foo from bar
where substring(col, 500,1)='1' and substring(col, 1500,1)='1';
这将是非常低效的,虽然,你可能要重新考虑你的架构。例如,可以分别作出折衷空间存储每个位速度...
create table foo
(
id int not null,
bar varchar(128),
primary key(id)
);
create table foobit
(
int foo_id int not null,
int idx int not null,
value tinyint not null,
primary key(foo_id,idx),
index(idx,value)
);
这将被查询
select foo.bar from foo
inner join foobit as bit500
on(foo.id=bit500.foo_id and bit500.idx=500)
inner join foobit as bit1500
on(foo.id=bit1500.foo_id and bit1500.idx=1500)
where
bit500.value=1 and bit1500.value=1;
显然消耗更多的存储空间,但应该快于那些查询操作作为指标将被使用。
我要转换的列多比特列和重写相关的代码 - 位掩码所以比字符串比较快得多。但是,如果你不能做到这一点,你必须使用特定的DB-功能。正则表达式可以是一种选择
-- Flavor: MySql
SELECT * FROM table WHERE column REGEXP "^.{499}1.{999}1"
select substring(your_col, 500,1) as char500,
substring(your_col, 1500,1) as char1500 from your_table;
不隶属于 StackOverflow