按位运算的替代方法
设想 : 我说有 4 个复选框,用户可以以任意组合选择这些复选框(他们也有权不选择任何一个复选框)。我必须将这 4 个选项存储到一列中。我认为最好的选择是使用二进制表示形式存储
option1 has the constant value 1
option2 has the constant value 2
option3 has the constant value 4
option4 has the constant value 8
因此,如果客户选择选项2和选项4,那么存储在数据库中的值将是2 + 8,即:10,如果客户选择选项1、选项4和选项8,则该值将是1 + 4 + 8,即 13。
我可以使用它
Select * from option_table where (option & 4)=4;
另外,当我从 mysql 查询时,如果我想检索选择 option3 的行,
。但由于某种原因,我无法使用这种方法,或者只是说我需要知道将这些多个值存储在单列中的下一个最佳选择是什么?
Scenario :
I have say 4 check boxes and users can select those checkboxes in any combination(they also have the power to not select even a single check box). I have to store these 4 options to a single column. I think the best option is to store using binary representation
option1 has the constant value 1
option2 has the constant value 2
option3 has the constant value 4
option4 has the constant value 8
So if the customer selects option2 and option4, then the value that is stored in the DB will be 2 + 8 ie: 10, if customer selects option1, option4 and option8 the value will be 1 + 4 + 8 which is 13.
Also when I query from mysql I can use
Select * from option_table where (option & 4)=4;
if I want to retrieve rows where option3 is selected.
But for some reason I cannot use this approach, or just say I need to know what's the next best option to store these multiple values in a single column ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种方法是素数相乘。要进行选择,您需要选择素数与列值的模数为 0 的列。
示例:
值 1: 2
值 2:3
值 3:5
值 4: 7
值 2 & 3 就是 3*5 = 15
值 1、2、3、4 将为 2*3*5*7 = 210
要获取值 1 所在的行,请选择
value % 2 == 0
An alternative could be to multiply prime numbers. To select, you would select columns where the modulus of the prime number into the value of the column is 0.
Example:
Value 1: 2
Value 2: 3
Value 3: 5
Value 4: 7
Value 2 & 3 would be 3*5 = 15
Values 1, 2, 3, 4 would be 2*3*5*7 = 210
To get the rows where value 1 is on, select where
value % 2 == 0
只要位数小于该列类型的位长度,您就可以始终使用此方法。如果要存储更多位,您可以使用多个列(字段)。
您还可以使用位字段。
You can always use this approach as long the number of bits is less equal than the bit length of the type for that column. If there are more bits to store you can use multiple columns(fields).
You can also use Bit Fields.