如何从数据库中查询 1 和 0 字符的数组?
假设您有一长串字符,要么是 1,要么是 0,有点像位向量,但位于数据库列上。 您如何查询以了解设置/未设置哪些值? 假设您需要知道 char 500 和 char 1500 是否为“true”。
Say you had a long array of chars that are either 1 or 0, kind of like a bitvector, but on a database column. How would you query to know what values are set/no set? Say you need to know if the char 500 and char 1500 are "true" or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
但是,没有索引可以用于此类查询。 当你有很多行时,这会很快变得很慢。
编辑:至少在 SQL Server 上,所有内置字符串函数都是确定性。 这意味着您可以研究基于整个组合值的 SUBSTRING() 结果创建计算列的可能性,为每个索引添加索引。 插入会变慢,表大小会增加,但搜索会非常快。
编辑#2:SQL Server 的限制是:
No index can be used for this kind of query, though. When you have many rows, this will get slow very quickly.
Edit: On SQL Server at least, all built-in string functions are deterministic. That means you could look into the possibility to make computed columns based on the SUBSTRING() results for the whole combined value, putting an index on each of them. Inserts will be slower, table size will increase, but searches will be really fast.
Edit #2: The limits for SQL Server are:
在 MySQL 中,使用 substring 像
这样但效率会相当低,您可能需要重新考虑您的架构。 例如,您可以单独存储每个位,以权衡空间和速度...
这将被查询
显然会消耗更多存储空间,但对于这些查询操作来说应该更快,因为将使用索引。
In MySQL, something using substring like
This will be pretty inefficient though, you might want to rethink your schema. For example, you could store each bit separately to tradeoff space for speed...
Which would be queried
Obviously consumes more storage, but should be faster for those query operations as an index will be used.
我会将列转换为多个位列并重写相关代码 - 位掩码比字符串比较快得多。 但如果您不能这样做,则必须使用特定于数据库的函数。 正则表达式可能是一种选择
I would convert the column to multiple bit-columns and rewrite the relevant code - Bit masks are so much faster than string comparisons. But if you can't do that, you must use db-specific functions. Regular expressions could be an option