我有一个 excel CSV 文件,我已经导入到数据库中。有一个名为组的字段,其中包括特定人员所属的所有组。这些组由 |(管道(字符。我想为每个搜索该组的人运行此字段,以查看他们是否属于该组,但我很难弄清楚如何创建一个循环来阅读所有这些。
表示例
------------------------------------
|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 '%|%|%|%';
这适用于最多四个长的列表,但可以轻松扩展到更多列表。
这是此方法的 SQL 小提琴。
或者,处理此问题的较短方法:
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
的大小。
这是此版本的SQL小提琴。
我使用 SQL Server 2014,所以不幸的是,我无法使用这些功能,但这个问题与我在这里找到的非常相似。
我想出了如何做一个嵌套循环来完成这个。
while ($row = mysqli_fetch_array($result)) {
//echo "im' in the Loop"; 回声 '' .$row[First_Name]。'' ;
echo '<td width="70">' . $row['Middle_Initial'] . '</td>';
echo '<td width="70">' . $row['Last_Name'] . '</td>';
echo '<td width="70">' . $row['External_ID'] . '</td>';
//Output all groups with loop
$str = $row['Groups'];
$wordChunks = explode("|", $str);
echo '<td width="10">';
for($i = 0; $i < count($wordChunks); $i++){
echo "$wordChunks[$i]" . '<br />';
}
'</td>';
echo '<td width="70">' . $row['User_ID'] . '</td>';
echo '<tr>';
} // End of Loop