from ( select g.uuid as groupUuid, g.name as name, gr.role as permission, gr.entity_uuid as entityUuid, gr.uuid as uuid from groups g left join group_roles gr on g.uuid = gr.group_uuid and gr.entity_uuid is null and gr.entity_uuid = #{query.entityUuid,jdbcType=VARCHAR} union all select 'Anyone' as groupUuid, 'Anyone' as name, gr.role as permission, gr.entity_uuid as entityUuid, gr.uuid as uuid from group_roles gr and gr.entity_uuid is null and gr.entity_uuid = #{query.entityUuid,jdbcType=VARCHAR} and gr.group_uuid is null ) sub left join () entity on sub.entityUuid = entity.uuid and lower(sub.name) like #{query.searchQueryToSqlLowercase,jdbcType=VARCHAR} ESCAPE '/' and sub.permission is not null and sub.entityUuid is null and entity.uuid = #{query.entityUuid,jdbcType=VARCHAR} and sub.permission = #{query.permission,jdbcType=VARCHAR} insert into group_roles ( uuid, group_uuid, entity_uuid, role ) values ( #{uuid,jdbcType=VARCHAR}, #{groupUuid,jdbcType=VARCHAR}, #{entityUuid,jdbcType=BIGINT}, #{role,jdbcType=VARCHAR} ) delete from group_roles where entity_uuid=#{entityUuid,jdbcType=VARCHAR} delete from group_roles where entity_uuid=#{entityUuid,jdbcType=VARCHAR} and group_uuid = #{groupUuid,jdbcType=VARCHAR} and group_uuid is null delete from group_roles where entity_uuid=#{entityUuid,jdbcType=VARCHAR} and role=#{permission,jdbcType=VARCHAR} delete from group_roles where role=#{permission,jdbcType=VARCHAR} and entity_uuid=#{entityUuid,jdbcType=BIGINT} entity_uuid is null and group_uuid=#{groupUuid,jdbcType=VARCHAR} group_uuid is null