mysql - 查询其中一张已转置的两张表
问题描述
我有以下表格,USER
并且RECORDS
. 该USER
表仅包含用户名和他们有权访问的组。如果用户的组为 null(例如 BOB),则表示他们是超级用户并且可以访问所有组。
用户:
username | group
---------|--------
Bob | (null)
Kevin | 1
John | 2
Mary | 1
然后我有一个RECORDS
包含记录列表的表:
record | field_name | value
----------------------------
1 AGE 92
1 HEIGHT 9'2
1 __GROUP__ 1
2 AGE 11
2 HEIGHT 1'1
2 __GROUP__ 2
3 AGE 68
3 HEIGHT 6'8
这不是我的设计,但这是我必须查询的。在RECORDS
表中,记录所属的组由__GROUP__
field_name 列中的值指示。所以我想做的是获取每个用户可以访问的所有记录的列表。
所以基于用户表:
BOB 可以访问所有记录
KEVIN 和 MARY 只能访问 field_name = '__ GROUP __' 且 value = 1 的记录
JOHN 只能访问 field_name = '__ GROUP __' 且 value = 2 的记录
这表示
- BOB 有权访问记录 1、2 和 3。
- 凯文只能访问记录 1
- Mary 只能访问记录 1
- 约翰只能访问记录 2
如果记录中缺少GROUP,则意味着只有超级用户(group = null 的用户)可以访问它。
我知道如果在RECORDS
表中它会有一个“GROUP”列,这会更容易,但不幸的是,这不是我的数据库,我无法更改结构。
**对不起,我忘了提到一个用户可以在多个组中!例如,玛丽可能在第 1 组和第 2 组中。
解决方案
一种选择使用exists
:
select u.*, r.*
from user u
cross join records r
where u.grp is null or exists (
select 1
from records r1
where
r1.ecord = r.record
and r1.field_name = '__GROUP__'
and r1.value = u.grp
)
这为您提供了每个用户有权访问的整个records
行。
如果您只想要记录 ID 列表,则可以使用聚合:
select u.userame, r.record
from users u
cross join records r
group by u.userame, u.grp, r.record
having
u.grp is null
or max(r.field_name = '__GROUP__' and r.value = u.grp) = 1
推荐阅读
- jquery - jquery创建对象动态不起作用
- c# - 在.Net Mvc C#中递归执行的动作过滤器
- speex - 如何将 .wav 转换为 .spx(speex) 文件
- javascript - Nuxt js客户端特定布局加载
- javascript - 如何将文件从 URL 保存到 blob
- azure-functions - Power 应用程序中的 Azure 函数响应返回真/假而不是值
- android - 使用 TensorflowInterfenceInterface 方法时无法解析方法“feed”
- gerrit - Gerrit 中没有修改的更改
- kubernetes - 为什么 Kuberenetes kubeadm init 命令无法从存储库 k8s.gcr.io 中提取图像
- wordpress - 从使用 cf7db 保存的 phpmyadmin 打印序列化数据