Q:

MYSQL union All with condition if condition matched choose first else 2nd

In my case it is  permissions and roles so i combined result with union all 
I just want check condition if user permission value = 0  then pick this else other one i am trying like this
SELECT username, orgId, uid, pid, perm FROM (
    SELECT users.username, users.orgId, user_roles.uid, role_perms.pid, role_perms.value AS perm
                    FROM user_roles INNER JOIN role_perms
                    ON (user_roles.rid = role_perms.rid) INNER JOIN user_users ON(user_roles.uid = users.uid) WHERE role_perms.pid = 9 AND users.orgId = 2 AND users.username IS NOT NULL AND users.username != ''
                    UNION ALL 
    SELECT users.username, users.orgId, user_perms.uid, user_perms.pid, user_perms.value AS perm
                    FROM user_perms INNER JOIN users ON(user_perms.uid = users.uid) WHERE user_perms.pid = 9 AND user_users.orgId = 2 AND user_users.username is not null and user_users.username != '') AS combPerm; 

It gives result as if permission is denied for one user in user_perm table but that user also have role that contain particular permission
username | orgId | uid | pid | perm
abc@a.com  2       11    9     0
abc@a.com  2       11    9     1
xyz@a.com  2       91    9     1
dvc@a.com  2       88    9     1

In result i want abc@a.com only one time if it has perm 0 from user_perms table and all other record same, desired result is as
 username | orgId | uid | pid | perm
abc@a.com  2       11    9     0
xyz@a.com  2       91    9     1
dvc@a.com  2       88    9     1

A:

You can just take the min(perm) and add a group by to your query     
SELECT username, orgId, uid, pid, min(perm) FROM (

 -----the rest of the query

) AS combPerm group by username, orgId, uid, pid;

