开发者

Making bitwise data more maintainable

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.


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:

SELECT * from TABLE WHERE Col & 4 = 4 


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:

CREATE TABLE thingType (
  id INTEGER AUTOINCREMENT,
  description varchar(20),
  PRIMARY KEY (id) UNIQUE KEY lookup (description)
);
CREATE TABLE hasThing (
  thing_id INTEGER, locn_id INTEGER
  PRIMARY_KEY (locn_id, thing_id)
);

Yes, its not nearly as effieicent on space - but its scalable, usable and adaptable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜