concat中的concat组

2vuwiymt  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(283)

数据库层次结构如下
学生姓名
分配给每个学生的费用清单
分配给每项费用的奖学金名单
作为结构,预期输出为
学名费->奖学金1,奖学金2

Karan-1.Annual Fee->Economic Scholarship,Incapable Scholarship,2.Monthly Fee

但我得到的
学名费->奖学金1,学名费->奖学金2

Karan-1.Annual Fee->Economic Scholarship,1.Annual Fee->Incapable Scholarship,2.Monthly Fee

这里怎么了?虽然我在筑巢 CONCAT ,但未获得预期输出

CONCAT(student.en_ttl,'-',GROUP_CONCAT(DISTINCT fee.id,'.',fee.en_ttl,
    COALESCE(CONCAT('->',sch.en_ttl),''))) AS fee

sql小提琴

4bbkushb

4bbkushb1#

你基本上需要两个层次的 GROUP BY . 所以,我们需要在这里使用一个派生表。第一个子查询将在 fee ; 然后第二级将在 student .
另外,在mysql的较新版本(并且符合ansi sql)中,您需要确保 SELECT 子句应该在 GROUP BY 条款。
查询

SELECT
  CONCAT(stud_ttl,'-',GROUP_CONCAT(CONCAT(fee_det, COALESCE(CONCAT('->',fee_sch), '')))) AS fee
FROM 
(
  SELECT  student.ttl AS stud_ttl, 
        CONCAT(fee.id,'.',fee.ttl) AS fee_det,   
        Group_concat(DISTINCT sch.ttl) AS fee_sch 
  FROM   inv_id
       JOIN student
         ON student.id = inv_id.std
       JOIN inv_lst
         ON inv_lst.ftm = inv_id.ftm
       JOIN fee
         ON fee.id = inv_lst.fee
       JOIN sec_fee
         ON sec_fee.fee = fee.id
            AND sec_fee.cls = student.cls
            AND sec_fee.sec = student.sec
       LEFT JOIN std_sch
              ON std_sch.std = student.id
       LEFT JOIN sec_sch
              ON sec_sch.sch = std_sch.sch
                 AND sec_sch.fee = fee.id
       LEFT JOIN sch
              ON sch.id = sec_sch.sch
  GROUP  BY student.ttl, fee_det, fee.ttl
) dt
GROUP BY stud_ttl;

结果

| fee                                                                  |
| -------------------------------------------------------------------- |
| Karan-1.Annual->Economic Scholarship,Incapable Scholarship,2.Monthly |

db fiddle视图

相关问题