使用MySQL CONCAT构建层级数据:新增层级语法修正求助
修正unit_group层级的CONCAT语法错误,构建正确的层级数据
问题分析
你新增的unit_group层级存在两个核心问题:
- CONCAT格式错误:拼接字符串时缺少逗号分隔符,导致层级标识格式混乱(比如
year:X后面直接接unit:Y,没有用逗号分隔) - 表关联缺失:
unit_group表只存储了unit_fk,无法直接获取institution_fk、year_fk、unit_code这些构建层级所需的字段,必须关联unit表
修正后的完整SQL
SELECT CONCAT('program:', p.program_pk) AS global_id, p.program_name AS name, NULL AS parent_global_id, NULL AS column_to_sort_by FROM program p UNION ALL -- institution SELECT CONCAT('institution:', i.institution_pk) AS global_id, i.institution_name, CONCAT('program:', i.program_fk) AS parent_global_id, NULL AS column_to_sort_by FROM institution i UNION ALL -- institution-year SELECT CONCAT('institution:', y.institution_fk, ',year:', y.year_pk) AS global_id, y.year_name, CONCAT('institution:', y.institution_fk) AS parent_global_id, NULL AS column_to_sort_by FROM year y UNION ALL -- institution-year-unit SELECT CONCAT('institution:', u.institution_fk, ',year:', u.year_fk, ',unit:', u.unit_code) AS global_id, u.unit_code, CONCAT('institution:', u.institution_fk, ',year:', u.year_fk) AS parent_global_id, NULL AS column_to_sort_by FROM unit u UNION ALL -- institution-year-unit-unit_group SELECT CONCAT('institution:', u.institution_fk, ',year:', u.year_fk, ',unit:', u.unit_code, ',unit_group:', ug.unit_group_pk) AS global_id, ug.unit_group, CONCAT('institution:', u.institution_fk, ',year:', u.year_fk, ',unit:', u.unit_code) AS parent_global_id, NULL AS column_to_sort_by FROM unit_group ug JOIN unit u ON ug.unit_fk = u.unit_pk -- 关联unit表获取层级所需字段
修正细节说明
- 补充分隔符:在
year:和unit:之间添加逗号,保持和上层一致的key:value格式(比如institution:1,year:5,unit:OPTM4101) - 关联unit表:通过
unit_fk关联unit表,获取构建层级必须的institution_fk、year_fk、unit_code字段 - 修正global_id标识:用
unit_group的主键unit_group_pk作为唯一标识(之前用ug.unit_fk是关联的unit主键,不是unit_group自己的ID) - 统一parent格式:parent_global_id完全匹配上层unit的global_id格式,确保层级关联正确
验证数据示例
根据你提供的测试数据,修正后的查询会生成如下格式的unit_group层级数据:
| global_id | name | parent_global_id |
|---|---|---|
| institution:1,year:5,unit:OPTM4101,unit_group:1 | Learning Events - OPTM4101 | institution:1,year:5,unit:OPTM4101 |
| institution:1,year:5,unit:OPTM4102,unit_group:2 | Learning Events - OPTM4102 | institution:1,year:5,unit:OPTM4102 |
内容的提问来源于stack exchange,提问作者IlludiumPu36
相关产品推荐
相关产品推荐

