多个复选框选项存储在数据库的单个字段中 [英] Multiple checkbox options stored into a single field in a database

查看:625
本文介绍了多个复选框选项存储在数据库的单个字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个技能表单,有12个复选框选项供您选择。

我使用HTML中的.jsp和Java中的一个servlet来处理jsp。从。
显然可以选择多于一个,并且我希望这些被发送到数据库。 (例如,Adam可以有Java和C ++,Bob只有Java)。

我想在数据库中只有一个字段包含所有复选框的信息。目前,我有技能作为一个字符串与分开它们,但是当我尝试检索信息时,我没有得到正确的信息背部。
例如,如果我搜索任何具有Java的员工,我会回到Bob的详细信息,但不是Adam的,因为它是字符串Java C ++的一部分,而不是单独的。



对于如何将多个复选框选项存储到数据库中的单个字段中,您有任何建议吗?但是可以将其分开以便于检索?

解决方案

当Jrod使用 LIKE 关键字可能会满足您的需求。



然而,从长远来看,还有其他方法可能会更好。

1-N关系

如果你在单独的表格您可以将它们连接成一对多关系,这意味着您可以按技能查询,然后将相关人员加入查询。这将使您能够进行更复杂的查询,例如能够搜索多个匹配技能或条件匹配技能,但不能搜索其他技能。

位标志正如你所说他们是复选框,我假设你的技能是有限的(通过复选框的数量)另一种方法是使用一个整数一个使用位标记 - 例如:

$ ul

  • Java = 1

  • C ++ = 2

  • Lisp` = 4

  • haskell = 8

  • Python = 16



  • 从所有复选框中累加累加值并将其存储为整数将允许您使用按位和(&)


    I'm using HTML in a .jsp and Java in a servlet to process the jsp.

    I have a form for Skills, with 12 checkbox options to choose from. Obviously more than one can be selected, and I want these then sent to a database. (As an example, Adam can have Java and C++ and Bob just has Java).

    I want only one field in my database to contain the information for all of the checkboxes. At the moment, I have the skills going in as one string with " " separating them, but then when I try to retrieve the info, I don't get the right info back. For example, if I search for any employee with "Java" I get back Bob's details but not Adam's, because it's part of a string "Java C++" instead of being separate.

    Do you have any suggestions on how to have multiple checkbox options stored into a single field in a database, but can be separated for easy retrieval?

    解决方案

    As Jrod pointed out using the LIKE keyword will likely satisfy your needs.

    However on a side note there are other ways that might be better in the long run.

    1-N relationship

    If you have your skills in a separate table you can then connect them in a one to many relationship, that would mean you could query by skill and then join the relevant people to the query. This would enable you to have more complex queries such as being able to search for more than one matching skill or conditional matching skill but not another skill.

    Bit flags

    As you say they are checkboxes I’m assuming your skills are limited (by the number of checkboxes) another approach is to use an integer an use bit flags – for example:

    • Java = 1
    • C++ = 2
    • Lisp` = 4
    • haskell = 8
    • Python = 16

    Adding up the accumulative value from all your checkboxes and storing this as an integer would allow you to query the database using a bitwise AND (&)

    这篇关于多个复选框选项存储在数据库的单个字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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