我的样本数据:
id role_id permission_id access_granted user_id
------------------------------------------------------------------
1 1 10 1 115
------------------------------------------------------------------
2 1 5 1 115
------------------------------------------------------------------
3 2 10 0 115
------------------------------------------------------------------
4 2 8 0 115
------------------------------------------------------------------
字符串
Group by with permission_id和结果应该有值true的重复permission_id行。正如我们所看到的,查询是按permission_id分组的,值为true的行被选择为permission_id 10,而对于其他行,permission_id没有被重复,所以值false被原样选择。
预期结果:
id role_id permission_id access_granted user_id
------------------------------------------------------------------
1 1 10 1 115
------------------------------------------------------------------
2 1 5 1 115
------------------------------------------------------------------
4 2 8 0 115
------------------------------------------------------------------
型
下面是我试图获取上述结果的查询。
select id, role_id, permission_id,
case when max(access_granted) = true then true else false end as access_granted,
user_id as user_id
from temp_permission group by permission_id;
型
需要优化和真实的查询,不会在任何情况下失败。
创建表查询
CREATE TABLE temp_permission (
id int auto_increment primary key,
role_id int,
permission_id int,
access_granted tinyInt(1),
user_id int
);
型
截图表的虚拟数据查询
INSERT INTO `temp_permission` (`id`, `role_id`, `permission_id`, `access_granted`, `user_id`) VALUES ('1', '1', '10', '1', '115');
INSERT INTO `temp_permission` (`id`, `role_id`, `permission_id`, `access_granted`, `user_id`) VALUES ('2', '1', '5', '1', '115');
INSERT INTO `temp_permission` (`id`, `role_id`, `permission_id`, `access_granted`, `user_id`) VALUES ('3', '2', '10', '0', '115');
INSERT INTO `temp_permission` (`id`, `role_id`, `permission_id`, `access_granted`, `user_id`) VALUES ('4', '2', '8', '0', '115');
型
如果无法将数据插入access_granted列,请替换1 = b'1' & 0 = b'0'
1条答案
按热度按时间tktrz96b1#
您可以简单地根据
permission_id
和access_granted
按降序对行进行排序,然后根据permission_id
选择不同的行。类似于:字符串
DB Fiddle