存储/查询二进制序列并使用掩码进行搜索
我找到了一种用二进制序列(例如 0b0101000
)在数据库中存储一些数据的好方法,并找到在应用掩码后给出积极结果的行。
例如: SELECT (0b0101010 & (1<<3 | 1<<5))>0;
允许我获取第三位或第五位打开的行,无论是否其他位打开或关闭。
问题是当我想用 ActiveRecord 执行此操作时。 此迁移 add_column :table, :column, :binary, :limit => 8.bytes
实际上创建了一个 TINYBLOB
列,而不是 BINARY
或 VARBINARY
并且我无法将掩码应用于其值,因为它不被视为二进制值。
我知道我可以通过执行原始 SQL 语句在迁移中制定正确的列格式,然后使用这部分的原始 SQL 段查询我的表,但这看起来不像“Rails 方式”。
谢谢你的任何想法。
I've found a good way to store some data in the database with a binary sequence, like 0b0101000
and find rows that give a positive result after applying a mask.
For exemple : SELECT (0b0101010 & (1<<3 | 1<<5))>0;
allows me to get rows with the 3rd or 5th bit on, no matter if the others bits are on or off.
The problem is when I want to do this with ActiveRecord.
This migration add_column :table, :column, :binary, :limit => 8.bytes
creates in fact a TINYBLOB
column and not a BINARY
or VARBINARY
and I can't apply my mask to its value because it is not considered a binary value.
I know that I could make the right column format in the migration by executing a raw SQL statement and then query my table with raw SQL segments for this part, but it doesn't seems like "the Rails Way".
Thanks for any idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,这不是最佳的,但至少可以将此序列存储在 TINYBLOB 列中。
我可以像这样查询数据库
例如,使用
10110110
列中的值和带有128
(100000000) 的掩码来选择该行。但我必须使用字符串构建查询的
conditions
部分;没有基于 has 的条件,也没有占位符。这是 Ruby 中的完整(虚拟)示例:
In fact, it's not optimal, but at least it works to store this sequence in the TINYBLOB column.
I can query the database like this
For example, with a value in the column of
10110110
and a mask with128
(100000000) the row is selected.But I had to build the
conditions
part of the query with a string ; no has-based conditions, and no placeholder.Here is a full (dummy) exemple, in Ruby :
你不能通过activerecord:
http ://www.packtpub.com/article/Working-with-Rails-ActiveRecord-Migrations-Models-Scaffolding-and-Database-Completion
见表:
迁移列类型|转换为 MySQL 字段类型 |可用选项1
:二进制 | TINYBLOB、BLOB、MEDIUMBLOB 或 LONGBLOB2 |极限=> 1 至 4294967296(默认 = 65536)2
you cant via activerecord:
http://www.packtpub.com/article/Working-with-Rails-ActiveRecord-Migrations-Models-Scaffolding-and-Database-Completion
see in the table :
Migration column type | Converts to MySQL field type | Available options1
:binary | TINYBLOB, BLOB, MEDIUMBLOB, or LONGBLOB2 | limit => 1 to 4294967296 (default = 65536)2