[英]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 |
+----+-------------------+----------------+-----------------+-----------------+
我們正在遷移到基於角色的授權,因此我們需要為上述現有數據找到新的角色。 角色是: 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
不為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.