Mysql如何处理单行有多个项目

标签 mysql sql

我有一个已导入数据库的 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/

相关文章:

Rnw文档中的SQL代码与knitr

php - 按自定义数组对行进行排序

php - 从Mysql中抓取结果,将链接内容转换为XML,然后输出

mysql - 对于 SQL 查询,使用 where 子句错误计数

php - 使用多个内连接

sql - 加入日期范围查询

c++ - Badly placed ()的错误

php - laravel eloquent ORM 中 where 约束的使用

mysql - 如何将单选按钮值写入 Sql 数据库?

c# - 将带有子查询的sql查询转换为linq语句