简体   繁体   中英

create mysql view for many-to-many relationship

MYSQL script to create a MYSQL view Table to show use id , email , and the assigned role/s name/s through many-to-many relationship

I wrote the script and joined tables to create the view table but it shows role name for the first record only the other users has null although they have roles!.

Tables

    users (id, email)
    roles (id, name)
    role_users (id, user_id, role_id)

My script

    DROP VIEW IF EXISTS users_view;
    CREATE VIEW users_view AS
       SELECT users.id AS user_id, users.email, roles_names.role_name 
         FROM users
    LEFT JOIN(
        SELECT role_users.user_id AS roles_user_id,
               role_users.role_id AS roles_role_id
          FROM role_users
    ) AS user_roles ON (roles_user_id = users.id)
    LEFT JOIN(
           SELECT roles.id AS roleid, roles.name AS role_name 
            FROM  roles
     ) AS roles_names ON (roleid = user_roles.roles_user_id)

view created success but it shows the role name for the first user only , other users has role_name value of null although they have records at role_users table

    SELECT u.id AS user_id, u.email, IFNULL(u_roles.role_name,'') as role_name 
      FROM users u 
 LEFT JOIN
        (SELECT GROUP_CONCAT(DISTINCT r.name SEPARATOR ',') as role_name, ur.user_id 
           FROM roles r INNER JOIN user_roles ur 
              ON r.id = ur.role_id 
       GROUP BY ur.user_id) u_roles 
              ON  u.id = u_roles.user_id

Since role users will be having all only roles from roles table, inner join on roles and user_roles will be fine. By this query all records which are having an entry in user_roles table will show role name and rest of the users will be having null as role name (adding IFNULL check to make null values an empty string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM