我有一张用户权限表。 这些权利可以是写或读。我有一个合并profile_user表和right_user表的SQL视图。该视图给我以下结果:
+-------+-----------+---------------+
| email | right | write_or_read |
+-------+-----------+---------------+
| admin | dashboard | write |
+-------+-----------+---------------+
| admin | dashboard | read |
+-------+-----------+---------------+
| admin | log | read |
+-------+-----------+---------------+
我如何不重复dashbord写入以仅获得最重要的写入权限(写入权限)。 我想编写一个SQL查询,它给我以下结果:
+-------+-----------+---------------+
| admin | dashboard | write |
+-------+-----------+---------------+
| admin | log | read |
+-------+-----------+---------------+
我读了this question,但答案仅涵盖id数字字段以获取正确的记录。
答案 0 :(得分:2)
在这种情况下,一个简单的max()
可以工作:
select email, right, max(write_or_read)
from user_rights
group by email, right;
答案 1 :(得分:1)
您可以使用CASE
表达式优先列出条件。这也适用于两个以上的值:
SELECT email, right, CASE
WHEN SUM(write_or_read = 'write') > 0 THEN 'write'
WHEN SUM(write_or_read = 'read') > 0 THEN 'read'
-- more conditions
END AS permission
FROM t
GROUP BY email, right