你如何从数据库中查询1和0的字符数组?

时间:2009-02-13 09:27:23

标签: database arrays bitvector

假设您有一长串的字符数,它们是1或0,有点像bitvector,但在数据库列上。您如何查询知道设置/未设置的值?假设您需要知道char 500和char 1500是否为“true”。

4 个答案:

答案 0 :(得分:6)

SELECT
  Id
FROM
  BitVectorTable
WHERE
  SUBSTRING(BitVector, 500, 1) = '1'
  AND SUBSTRING(BitVector, 1000, 1) = '1'

但是,没有索引可用于此类查询。当你有很多行时,这会很快变慢。

编辑:至少在SQL Server上,所有内置字符串函数都是deterministic。这意味着您可以根据整个组合值putting an index on each of them的SUBSTRING()结果来研究计算列的可能性。插入内容会变慢,表格大小会增加,但搜索速度会非常快。

SELECT
  Id
FROM
  BitVectorTable
WHERE
  BitVector_0500 = '1'
  AND BitVector_1000 = '1'

编辑#2:limits for SQL Server是:

  • 每个普通表1,024列
  • 每“宽”表的30.000列

答案 1 :(得分:3)

在MySQL中,使用substring之类的东西,比如

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;

显然会消耗更多存储空间,但对于那些查询操作应该更快,因为将使用索引。

答案 2 :(得分:2)

我会将列转换为多个位列并重写相关代码 - 位掩码比字符串比较快得多。但是如果你不能这样做,你必须使用特定于数据库的功能。正则表达式可以是一个选项

-- Flavor: MySql
SELECT * FROM table WHERE column REGEXP "^.{499}1.{999}1"

答案 3 :(得分:1)

select substring(your_col, 500,1) as char500,
substring(your_col, 1500,1) as char1500 from your_table;