mysql - Select only one row from a join based on foreign condition -


the main idea

  • user hasmany roles (data stored in tables: users, roles, user_role)
  • i want know if user admin or client
  • this data joined different result

what i'm doing

select   `users`.`id`,   `users`.`name`,   `roles`.`display_name` `users`   join role_user on users.id = role_user.user_id   join roles on role_user.role_id = roles.id 

why it's wrong

because result get

id       name    display name  1       admin    admin 1       admin    client 2       admin2   admin 2       admin2   client 3       client   client 7       test     admin 7       test     client 

what want

id       name   display name  1       admin   admin 2       admin2  admin 3       client  client 7       test    admin 

how i'm working make work

  • using aggregates somehow
  • using cases somehow
  • joining subset of data somehow

thank idea !

[update] here sqlfiddle describing issue.

select       `users`.`id`,       `users`.`name`,       `roles`.`display_name` `users` left join role_user on users.id = role_user.user_id left join roles on role_user.role_id = roles.id 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -