MySQL选择值不为0的所有列

时间:2013-06-19 16:03:33

标签: mysql

好的,我有一个权限表,其中列数可以波动。页面上有一个依赖于此表的导航栏。有些人可以看到一些模块,有些人看不到,等等。我想要推出的是选择值不是0的所有列。

table modperm
     uid 1234
     module1 0
     module2 2
     module3 1
     module4 0
     module5 0
     module6 1
...
...
...

有没有办法做类似

的事情
SELECT * FROM `modperm` WHERE `uid`='1234' AND value<>0

2 个答案:

答案 0 :(得分:0)

您可以尝试这个长时间的查询,但它可能对您有帮助。

select uid , group_concat(val) as vals from (
SELECT uid, module1 AS val
FROM  modperm
WHERE module1 !=0
and uid = 1234

UNION ALL
SELECT uid , module2 
FROM  modperm 
WHERE module2 !=0
and uid = 1234

UNION ALL
SELECT uid, module3 
FROM  modperm
WHERE module3 != 0
and uid = 1234

UNION ALL
SELECT uid ,module4 
FROM  modperm 
WHERE module4 !=0
AND uid = 1234

UNION ALL
SELECT uid, module5 AS val
FROM  modperm
WHERE module5 !=0
and uid = 1234

UNION ALL
SELECT uid ,module6 
FROM  modperm 
WHERE module6 !=0
and uid =1234
)t

demo

如果你想要显示模块名称

this demo

答案 1 :(得分:0)

    select * from modperm;
    select uid, 
    case when module1 != 0 then 'valid' else 'invalid' end as module1 ,
    case when module2 != 0 then 'valid' else 'invalid' end as module2 ,
    case when module3 != 0 then 'valid' else 'invalid' end as module3 ,
    case when module4 != 0 then 'valid' else 'invalid' end as module4 ,
    case when module5 != 0 then 'valid' else 'invalid' end as module5 ,
    case when module6 != 0 then 'valid' else 'invalid' end as module6
    .............
    from modperm where uid = 1234;

Fiddle