mysql - 如何从现有数据创建新的逗号分隔列?

标签 mysql sql

我们有以下 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            |
+----+-------------------+----------------+-----------------+-----------------+

我们正在迁移到基于角色的授权,因此我们需要为上述现有数据找到新的角色。角色是:AUTHOREDITORADMIN。一个用户可以链接到多个角色。角色将存储为逗号分隔值(顺序无关紧要)。在上面的数据中,输出应该是:

+----+-------------------+---------------+----------------+-----------------+-----------------+
| 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/

相关文章:

php - 在 php 中存储一个全局值

sql - Postgres Select语句的列不存在

mysql - mysql中的插入语句为每个插入递增

MySQL WHERE NOT EXISTS 错误

sql - 如何插入 Select every with TOP() 子句

SQL问题——select across multiple tables (user groups)

c# - 在 C# 代码后面的 LIKE SQl 查询中转义单引号

mysql - SQL - 计数不返回零

mysql - 从时间序列数据中获取高于阈值的时间量

mysql - 加快慢速更新查询