search

Home  >  Q&A  >  body text

mysql - Is it necessary to set a separate column as the primary key for the intermediate relational table in the database?

For example, the common roles and users are associated with the role user association table. The fields are as follows:
role_id
user_id

When there are these two fields, is it necessary to set a separate column of id as the primary key?

phpcn_u1582phpcn_u15822715 days ago1151

reply all(4)I'll reply

  • 某草草

    某草草2017-06-22 11:56:41

    No need.
    But you can index both fields to speed up queries.

    reply
    0
  • 高洛峰

    高洛峰2017-06-22 11:56:41

    Every table should have a primary key, preferably an auto-incremented primary key

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-22 11:56:41

    As far as the paradigm of database design is concerned, I think if these two IDs can form a primary key, there is no need to add another ID.

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-22 11:56:41

    If there is a many-to-many relationship between user and role:

    CREATE TABLE user_role (
        user_id INTEGER NOT NULL,
        role_id INTEGER NOT NULL,
        PRIMARY KEY (user_id, role_id),
        KEY (role_id)
    );
    

    In this way, you can not only check all permissions of a certain user, but also check all users with certain permissions (such as super administrator).

    reply
    0
  • Cancelreply