How to store multiple values in single column where use less memory?

后端 未结 4 1481
滥情空心
滥情空心 2021-01-02 21:40

I have a table of users where 1 column stores user\'s \"roles\". We can assign multiple roles to particular user.

Then I want to store role IDs in

4条回答
  •  一向
    一向 (楼主)
    2021-01-02 22:41

    If a user can have multiple roles, it is probably better to have a user_role table that stores this information. It is normalised, and will be much easier to query.

    A table like:

    user_id | role
    --------+-----------------
          1 | Admin
          2 | User
          2 | Admin
          3 | User
          3 | Author
    

    Will allow you to query for all users with a particular role, such as SELECT user_id, user.name FROM user_role JOIN user WHERE role='Admin' rather than having to use string parsing to get details out of a column.

    Amongst other things this will be faster, as you can index the columns properly and will take marginally more space than any solution that puts multiple values into a single column - which is antithetical to what relational databases are designed for.

    The reason this shouldn't be stored is that it is inefficient, for the reason DCoder states on the comment to this answer. To check if a user has a role, every row of the user table will need to be scanned, and then the "roles" column will have to be scanned using string matching - regardless of how this action is exposed, the RMDBS will need to perform string operations to parse the content. These are very expensive operations, and not at all good database design.

    If you need to have a single column, I would strongly suggest that you no longer have a technical problem, but a people management one. Adding additional tables to an existing database that is under development, should not be difficult. If this isn't something you are authorised to do, explain to why the extra table is needed to the right person - because munging multiple values into a single column is a bad, bad idea.

提交回复
热议问题