我有两个表,tblStudent和tblDepartment。我将DeptIds以逗号分隔值的形式存储在学生表中,例如-
StudentId DeptIds
1 1,2,3
2 4
3 1,5
我想在学生表的GetById过程中用逗号而不是DeptIds分隔部门名称。有什么帮助吗?
答案 0 :(得分:3)
DeptIds
CSV列值从您的问题中可以看出,这是非常不切实际的,使用更好的数据模型是永远不会发生的。
我建议使用以下数据模型:
这样,您将使用tblStudentDept
表逐行存储有关特定部门中学生角色的数据:
ID StudentId DeptIds
1 1 1
2 1 2
3 1 3
4 2 4
5 3 1
6 3 5
LISTAGG
函数显示CSV数据对于ID,就像以前一样:
在WITH AS
中带有测试数据示例的代码:
WITH tblStudentDept AS(
select 1 as id, 1 as StudentID, 1 as DeptID from dual
union all
select 2 as id, 1 as StudentID, 2 as DeptID from dual
union all
select 3 as id, 1 as StudentID, 3 as DeptID from dual
union all
select 4 as id, 2 as StudentID, 4 as DeptID from dual
union all
select 5 as id, 3 as StudentID, 1 as DeptID from dual
union all
select 6 as id, 3 as StudentID, 5 as DeptID from dual
)
SELECT sd.StudentID, LISTAGG(DeptID, ',') WITHIN GROUP (ORDER BY sd.DeptID)
FROM tblStudentDept sd
GROUP BY sd.StudentID;
按部门要求输入部门名称:
使用WITH AS
表和希望新建的tblDepartment
表之间的连接,在tblStudentDept
中包含测试数据示例的代码:
WITH tblStudentDept AS(
select 1 as id, 1 as StudentID, 1 as DeptID from dual
union all
select 2 as id, 1 as StudentID, 2 as DeptID from dual
union all
select 3 as id, 1 as StudentID, 3 as DeptID from dual
union all
select 4 as id, 2 as StudentID, 4 as DeptID from dual
union all
select 5 as id, 3 as StudentID, 1 as DeptID from dual
union all
select 6 as id, 3 as StudentID, 5 as DeptID from dual
),
tblDepartment AS(
select 1 as DeptId, 'Dept-1' as DeptName from dual
union all
select 2 as DeptId, 'Dept-2' as DeptName from dual
union all
select 3 as DeptId, 'Dept-3' as DeptName from dual
union all
select 4 as DeptId, 'Dept-4' as DeptName from dual
union all
select 5 as DeptId, 'Dept-5' as DeptName from dual
)
SELECT sd.StudentID, LISTAGG(d.DeptName, ',') WITHIN GROUP (ORDER BY sd.DeptID) as DeptNames
FROM tblStudentDept sd
JOIN tblDepartment d
ON (d.DeptId = sd.DeptId)
GROUP BY sd.StudentID;
代码输出:
StudentId DeptNames
1 Dept-1,Dept-2,Dept-3
2 Dept-4
3 Dept-1,Dept-5
希望我能帮上忙!