MYSQL union All with condition if condition matched choose first else 第二个

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

在我的例子中,它是权限和角色,所以我将结果与 union all 结合起来 我只想检查条件,如果用户权限值 = 0,然后选择其他我正在尝试的另一个

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; 

它给出的结果好像 user_perm table 中的一个用户的权限被拒绝,但该用户也有包含特定权限的角色

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

结果我只想要 abc@a.com 一次,如果它有来自 user_perms table 的 perm 0 和所有其他记录相同,期望的结果是

 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

SELECT * FROM (YOUR QUERY) t WHERE perm=0 GROUP BY username, orgId, uid,pid;

您只需使用 min(perm) 并在您的查询中添加分组依据

SELECT username, orgId, uid, pid, min(perm) FROM (

 -----the rest of the query

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

您已经接受了 isaace 关于如何使 perm 0 优先于 perm 1 的回答。但是现在您说,您宁愿使查询 2 结果优先于查询 1 结果。

在标准 SQL 中,这很容易完成。您将向查询 (select 1/2 as rankkey, ...) 添加排名键并使用 ROW_NUMBER 对您的结果进行排名并保持最佳匹配,或者您将使用 FETCH WITH TIES.

进行此操作

MySQL 既不支持 window 函数,例如 ROW_NUMBER,也不支持允许连接的限制子句。 MySQL 中的查询中的变量可以解决许多此类问题。这是另一个技巧:

你有的是这样的

select username, orgId, uid, pid, perm from table1
union all
select username, orgId, uid, pid, perm from table2;

isaace 向您展示了如何获得每个用户名、orgId、uid、pid 的最小权限。然而,你想要一些接近但不同的东西:-)给你:

select username, orgId, uid, pid, max(keyperm) % 10 as perm
from
(
  select username, orgId, uid, pid, perm + 10 as keyperm from table1
  union all
  select username, orgId, uid, pid, perm + 20 as keyperm from table2
)
group by username, orgId, uid, pid
order by username, orgId, uid, pid;

这里发生了什么?你看,我在第一个查询中将 10 加到 perm,在第二个查询中将 20 加到 perm。 MAX 给了我两者中较高的一个,如果两者都存在,则为第二个。我们最终得到一个 10 或 11 或 20 或 21 的烫发。操作 % 10(模十)删除十的位置,只保留一个的位置,即 0 或 1,即烫发。

(如果 perms 可以是两位数,则将 100 和 200 相加并使用 %100,如果更多位数......那么你明白了。)