1

假设您有一长串 1 或 0 的字符,有点像位向量,但在数据库列上。您将如何查询以了解已设置/未设置哪些值?假设您需要知道 char 500 和 char 1500 是否为“真”。

4

4 回答 4

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

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

编辑:至少在 SQL Server 上,所有内置字符串函数都是确定性的。这意味着您可以研究根据 SUBSTRING() 结果为整个组合值创建计算列的可能性,并在每个列上放置一个索引。插入会变慢,表大小会增加,但搜索会非常快。

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

编辑 #2:SQL Server 的限制是:

  • 每个普通表 1,024 列
  • 30.000 columns per "wide" table
于 2009-02-13T09:37:13.810 回答
3

在 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;

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

于 2009-02-13T09:35:44.967 回答
2

我会将列转换为多个位列并重写相关代码 - 位掩码比字符串比较快得多。但是如果你不能这样做,你必须使用 db-specific 函数。正则表达式可能是一种选择

-- Flavor: MySql
SELECT * FROM table WHERE column REGEXP "^.{499}1.{999}1"
于 2009-02-13T09:36:27.073 回答
1
select substring(your_col, 500,1) as char500,
substring(your_col, 1500,1) as char1500 from your_table;
于 2009-02-13T09:40:55.190 回答