mysql - How to "remove duplicates" from a UNION query -
i have 2 tables in mysql: 1 called gtfsws_users
contains users system i'm developing , called gtfsws_repository_users
contains roles these users.
gtfsws_users
has these fields: email, password, name, is_admin , enabled. gtfsws_repository_users
has: user_email, repository_id , role.
the role
integer defines privileges on gtfs repository (public transportation data, not relevant problem).
one important thing every administrator accont (that is, every user has is_admin
flag set 1
in gtfsws_users
) has full access repositories.
now, users registered in gtfsws_repository_users
have access specific repository defined there (unless administrators, of course). 1 user can have multiple repositories him/her can access.
what i'm trying all users access specific repository (it doesn't matter type of role
user has, want know if can access repository or not). i'm writing sql statement getting them:
( select distinct gtfsws_users.email email, gtfsws_users.name name, gtfsws_users.is_admin is_admin, gtfsws_users.enabled enabled, gtfsws_repository_users.role role gtfsws_users inner join gtfsws_repository_users on gtfsws_users.email = gtfsws_repository_users.user_email gtfsws_repository_users.repository_id = '2' ) union ( select email, name, is_admin, enabled, null role gtfsws_users is_admin = 1 )
now, works fine users access different repositories. gets administrators too.
the problem when have administrator registered in gtfsws_repository_users
, because duplicated.
so example, have in gtfsws_users
:
('test@test.com', '*****', 'real name', 1, 1)
and user registered in gtfsws_repository_users
this:
('test@test.com', 2, 10)
when select
in mysql (using union
add administrators) get:
('test@test.com', 'real name', 1, 1, 10) ('test@test.com', 'real name', 1, 1, null)
what need filter table remove duplicates, getting only:
('test@test.com', 'real name', 1, 1, null)
yes, getting null
role (since ignored user administrator).
does have clue on how achieve that? lot.
edit: ok, katrin's suggestion, i'm getting progress. 1 row, it's 1 role
number defined. way preserve 1 null
role instead of defined one?
since aggregate functions ignore null values, can convert null number can extracted min or max.
assuming roles greater 0:
select email, name, is_admin, enabled, nullif(min(coalesce(role, 0)), 0) role (( select distinct gtfsws_users.email email, gtfsws_users.name name, gtfsws_users.is_admin is_admin, gtfsws_users.enabled enabled, gtfsws_repository_users.role role gtfsws_users inner join gtfsws_repository_users on gtfsws_users.email = gtfsws_repository_users.user_email gtfsws_repository_users.repository_id = '2' ) union ( select email, name, is_admin, enabled, null role gtfsws_users is_admin = 1 )) q group email, name, is_admin, enabled
Comments
Post a Comment