如何在MySql数据库中存储布尔值数组? [英] How can I store an array of boolean values in a MySql database?

查看:205
本文介绍了如何在MySql数据库中存储布尔值数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的情况下,每个项目都有一个属性,不是。属性可以是几百个,所以我需要说每个项目最多1000个真/假位。



有没有办法将这些位存储在项目的一个字段中?

解决方案

如果您正在寻找一种可以搜索的方式,那么不需要。 b
$ b

几种可搜索的方法(涉及超过1列和/或表):




  • 使用一堆 SET 列。您可以在一组中限制64个项目(开/关),但是您可能会想出一个将其分组的方法。

  • 使用3个表:项目(id,...) ),FlagNames(id,name)和一个数据透视表ItemFlags(item_id,flag_id)。然后,您可以使用加入查询项目。



如果您不需要它可搜索,那么您需要的是在将数据放入数据库之前序列化数据的方法,并且在将其拉出时将其排序后,然后使用char或varchar列。




  • 使用内置的语言(PHP

  • 将一系列y和n个字符连在一起。

  • 将值包装到字符串中在调用MySQL数据库之前,在客户端中调用8位/字符),并在从数据库中检索数据时对其进行解包。这是最有效的存储机制(如果所有行都相同,请使用char [x],而不是varchar [x]),代价是不可搜索的数据和稍微复杂的代码。


In my case, every "item" either has a property , or not. The properties can be some hundreds, so I will need , say, max 1000 true/false bits per item.

Is there a way to store those bits in one field of the item ?

解决方案

If you're looking for a way to do this in a way that's searchable, then no.

A couple searchable methods (involving more than 1 column and/or table):

  • Use a bunch of SET columns. You're limited to 64 items (on/offs) in a set, but you cna probably figure out a way to group them.
  • Use 3 tables: Items (id, ...), FlagNames(id, name), and a pivot table ItemFlags(item_id, flag_id). You can then query for items with joins.

If you don't need it to be searchable, then all you need is a method to serialize your data before you put it in the database, and a unserialize it when you pull it out, then use a char, or varchar column.

  • Use facilities built in to your language (PHP's serialize/unserialize).
  • Concatenate a series of "y" and "n" characters together.
  • Bit-pack your values into a string (8 bits per character) in the client before making a call to the MySQL database, and unpack them when retrieving data out of the database. This is the most efficient storage mechanism (if all rows are the same, use char[x], not varchar[x]) at the expense of the data not being searchable and slightly more complicated code.

这篇关于如何在MySql数据库中存储布尔值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆