我有一个已导入数据库的 Excel CSV 文件。有一个名为 groups 的字段,其中包含特定人员所属的所有组。这些组由 | 分隔(管道)字符。我想为每个搜索该组的人遍历此字段,看看他们是否属于该组,但我很难弄清楚如何创建一个循环来通读所有这些组。
表格示例
------------------------------------
|Name | Groups |
------------------------------------
|Bob | Cleaning|Plumber |
|Sue | Admin|Secretary|Pay_role |
|Joe | Engineer |
|Frank | Plumber|Admin |
|James | Plumber|Carpenter |
我想出了如何在 | 之前捕获第一组但我不知道之后如何阅读每个字段
SELECT substring(Groups,1,((instr(Groups,'|')-1))) as ExtractString
来自 DB_groups
将来我想将人员添加到组中并从组中删除人员,因此我正在寻找一个查询,使我能够看到每个人的组,例如:
Sue | Admin
Sue | Secretary
Sue | Pay_r
奥莱
也许有更好的方法来执行此操作,但 CSV 文件有 25k 条记录,所以我有点受困于其中已有的内容。谢谢您的帮助。
最佳答案
一种方法在 SQL 中是这样的:
select name, substring_index(groups, '|', 1)
from t
union all
select name, substring_index(substring_index(groups, '|', 2), '|', -1)
from t
where groups like '%|%'
union all
select name, substring_index(substring_index(groups, '|', 3), '|', -1)
from t
where groups like '%|%|%'
union all
select name, substring_index(substring_index(groups, '|', 4), '|', -1)
from t
where groups like '%|%|%|%';
这适用于最多四个长度的列表,但它可以很容易地扩展到更多。
Here是此方法的 SQL Fiddle。
或者,更短的处理方式:
select name, substring_index(substring_index(groups, '|', n.n), '|', -1) as grp
from t cross join
(select 1 as n union all select 2 union all select 3 union all select 4
) n
where n.n >= (length(groups) - length(replace(groups, '|', '')))
要添加更多组,只需增加 n
的大小即可。
Here是这个版本的 SQL Fiddle。
关于Mysql如何处理单行有多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181253/