[英]MySQL select all column names where condition is met for specific row
您可以使用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
像这样的东西
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
)
您可以将concat_ws()
与case
表达式一起使用:
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;
请注意,您的数据模型有问题。 如果您正确存储了这些数据,那么解决方案会更简单。 存储它的正确方法是每个用户的每个“组”和“级别”一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.