使按位数据更易于维护
我的表中有大量布尔字段,其中包含度假地点列表。由于数据是通过ajax从浏览器获取的,并且我希望有很多移动用户,因此我将它们组合成整数以供按位运算符使用。因为字段太多(超过 32 个),所以我必须对字段进行分组并为每个组生成一个整数。因此(在简化的伪代码中(我实际上使用的是 php))
[ hasCar: 1, hasBoat: 0, hasTree: 0, hasCat: 1, hasHorse: 0]
将映射到类似
[
things: int("100"),
animals: int("10")
]
我将这些整数存储在数据表中的其他字段中的内容。这样做的问题是它非常不灵活。例如,如果我更改布尔字段的分组方式,或者删除一个布尔字段,我必须重新生成所有整数并覆盖每一项的数据。
对于如何以高效、可维护的方式处理按位数据的生成,有人有什么好主意吗?
I have a large number of boolean fields in my table containing a list of holiday locations. As the data is fetched from the browser by ajax and I hope to have a lot of mobile users, I've combined them into integers to be used by bitwise operators. Because there are so many fields though (more than 32) I've had to group the fields and generate an integer for each group. So (in simplified pseudo code (I'm actually using php))
[ hasCar: 1, hasBoat: 0, hasTree: 0, hasCat: 1, hasHorse: 0]
will map to something like
[
things: int("100"),
animals: int("10")
]
I store those integers in additional fields in my data table. The problem with this is that it is very inflexible. e.g. if I change how I group my boolean fields, or remove one I have to regenerate all the integers and overwrite the data for each item.
Does anyone have any good ideas for how to handle generation of bitwise data in an efficient, maintainable way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了有效地使用按位运算符,请指定从 2^0、2^1、2^2、... 开始的值,即 1、2、4、8、16、...
现在,当您将这些值存储在数据库中时,可以将这些值求和并存储在列中。
例如,如果您有这些价值观
[ hasCar: 1, hasBoat: 2, hasTree: 4, hasCat: 8, hasHorse: 16]
想要查询用户是否有Tree,可以使用以下查询:
For using Bitwise operator effeciently, assign the values starting from 2^0, 2^1, 2^2, ... i.e. 1, 2, 4, 8, 16, ...
Now when you are storing these values in db, these values can be summed up and stored in a column.
So e.g. if you had these values
[ hasCar: 1, hasBoat: 2, hasTree: 4, hasCat: 8, hasHorse: 16]
and wanted to query if the user hasTree, you could use the following query:
这与数据库规范化背道而驰。
当然,它有效地利用了空间,但是如果你想用“hasCat”查询所有记录怎么办?使用 Tushar 的枚举,并在 SQL 中执行布尔运算,您必须对每个查询运行全表扫描。
设置单独的 2 张桌子:
是的,它在空间上的效率并不高,但它具有可扩展性、可用性和适应性。
This flies in the face of database normalization.
Sure it makes efficient use of the space, but what if you want to query all the records with 'hasCat'? Using Tushar's enumerations, and doing the boolean arith in SQL you'll have to run a full table scan for every query.
Set up a separate 2 tables:
Yes, its not nearly as effieicent on space - but its scalable, usable and adaptable.