【问题标题】:Group_Concat multple columns in sqlGroup_Concat sql中的多列
【发布时间】:2020-07-16 02:57:09
【问题描述】:

我有两张桌子。

第一个表称为 Employee

|EID|姓名|工资 | ========================== |1 |A |300 | |2 |B |400 | |3 |O |500 |

第二张表称为 Employee_Sal_Changes

|EID| Salary_Change_History|年 ======================================== |1 |100 |2012 |1 |200 |2013 |1 |300 |2014 |2 |200 |2013 |2 |400 |2014 |3 |100 |2011 |3 |200 |2012 |3 |300 |2013 |3 |500 |2014

在我的前端表上,我想展示

id |薪资变动历史 | ================================== 一个 | 100:2012 | | 200:2013 | | 300:2014 | ================================== 乙| 200:2013 | | 400:2014 | ================================== ○ | 100:2011 | | 200:2012 | | 300:2013 | | 400:2014 | ==================================

我想将salary_change_history 和year 匹配到EID 并使用循环将它们显示在前端。

为了获得这些,我尝试使用 group_concat 将它们存储在一个数组中,但它只获取 EID = 1 的值

这是后端的查询

Select 
(select Group_Concat(Employee_Sal_Changes.Salary_Change_History),(Group_Concat(Employee_Sal_Changes.year) from Employee_Sal_Changes left join Employee on Employee_Sal_Changes.EID = Employee.EID), 
Employee.EName
From Employee_Sal_Changes

有更好的方法还是继续使用 group_concat?

【问题讨论】:

    标签: mysql sql group-by group-concat


    【解决方案1】:

    你可以使用聚合:

    select 
        eid, 
        group_concat(
            year, ':', salary_change_history 
            order by year
            separator '\n'
        ) salary_change_history
    from employee_sal_changes
    group by eid
    

    对于每个员工,这会生成一个由回车分隔的<year>:<salary> 值列表。请注意,您不需要引入 employee 表来生成该结果集:另一个表包含所有必要的信息。

    Demo on DB Fiddle


    如果您还想要员工姓名:

    select 
        s.eid, 
        e.ename,
        group_concat(
            s.year, ':', s.salary_change_history 
            order by s.year
            separator '\n'
        ) salary_change_history
    from employee_sal_changes s
    inner join employee e on e.eid = s.eid
    group by s.eid, e.ename
    

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2022-11-22
      • 2013-09-21
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2010-10-30
      相关资源
      最近更新 更多