簡體   English   中英

如何從現有數據創建新的逗號分隔列?

[英]How to create new comma-separated column from existing data?

我們有以下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不為null,則添加角色AUTHOR
  • 如果editor_for_blog不為null,則添加角色EDITOR
  • 如果admin_for_blog不為null,則添加角色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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM