我们有以下account
表(MySQL RDBMS):
+----+-------------------+----------------+-----------------+-----------------+
| id | username | admin_for_blog | editor_for_blog | author_for_blog |
+----+-------------------+----------------+-----------------+-----------------+
| 1 | author_only | NULL | NULL | 1 |
| 2 | editor_and_author | NULL | 2 | 2 |
| 3 | admin_only | 3 | NULL | NULL |
+----+-------------------+----------------+-----------------+-----------------+
我们正在迁移到基于角色的授权,因此我们需要找到上述现有数据的新角色。角色为:AUTHOR
,EDITOR
和ADMIN
。用户可以链接到多个角色。角色将以逗号分隔的值存储(顺序并不重要)。在上面的数据中,输出应为:
+----+-------------------+---------------+----------------+-----------------+-----------------+
| id | username | roles | admin_for_blog | editor_for_blog | author_for_blog |
+----+-------------------+---------------+----------------+-----------------+-----------------+
| 1 | author_only | AUTHOR | NULL | NULL | 1 |
| 2 | editor_and_author | AUTHOR,EDITOR | NULL | 2 | 2 |
| 3 | admin_only | ADMIN | 3 | NULL | NULL |
+----+-------------------+---------------+----------------+-----------------+-----------------+
基本上是这样的:
author_for_blog
不为空,则添加角色AUTHOR
editor_for_blog
不为空,则添加角色EDITOR
admin_for_blog
不为空,则添加角色ADMIN
有关如何做到这一点的任何提示?我已经能够为每个用户附加一个角色,但我无法找到一种方法来管理以逗号分隔的多个角色:
select username,
case admin_for_blog is not null when true then 'ADMIN' else
case editor_for_blog is not null when true then 'EDITOR' else
case author_for_blog is not null when true then 'AUTHOR' else
'error!' end end end
from account
答案 0 :(得分:3)
您可以使用跳过concat_ws
值的函数null
。
select username,
concat_ws(','
,case when admin_for_blog is not null then 'ADMIN' end
,case when editor_for_blog is not null then 'EDITOR' end
,case when author_for_blog is not null then 'AUTHOR' end
)
from account