我们有以下 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
最佳答案
您可以使用函数 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
关于mysql - 如何从现有数据创建新的逗号分隔列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43471182/