我有一个将用户链接到组的表,其设置如下:

我想知道是否有一种方法可以选择满足特定条件的所有groupID(列名)。
例如,如果我想查找用户2的级别大于0的所有组,它将返回(1,2,4)
还值得注意的是,它不能手动完成,因为大约有5000行和120列
谢谢你的帮助!
发布于 2020-09-12 17:17:04
您可以使用union all取消透视和搜索。假设表中的列名为grp1到grp5
select 1 as grp from t where userid = 2 and grp1 > 0
union all select 2 from t where userid = 2 and grp2 > 0
union all select 3 from t where userid = 2 and grp3 > 0
union all select 4 from t where userid = 2 and grp4 > 0
union all select 5 from t where userid = 2 and grp5 > 0您应该考虑修复您的数据模型。每个用户/组元组应该存储在桥接表中的单独行中,如下所示:
user_groups
userid grp val
1 1 3
1 2 2
1 3 2
1 4 2
1 5 0
...然后,查询就像这样简单:
select grp from user_groups where userid = 2 and val > 0发布于 2020-09-12 17:07:22
像这样的东西
select distinct group from (
select group1 group from t where level > 0
union
select group2 from t where level > 0
union
select group3 from t where level > 0
union
select group4 from t where level > 0
union
select group5 from t where level > 0
)发布于 2020-09-12 19:10:44
您可以在case表达式中使用concat_ws():
select concat_ws(',',
case when `1` > 0 then 1 end,
case when `2` > 0 then 2 end,
case when `3` > 0 then 3 end,
case when `4` > 0 then 4 end,
case when `5` > 0 then 5 end
)
from t
where userid = 2;请注意,我们的数据模型有一个问题。如果您正确地存储了这些数据,那么解决方案将会更简单。正确的存储方式应该是每个用户的"group“和"level”占一行。
https://stackoverflow.com/questions/63858648
复制相似问题