mysql - group,但显示列的所有行

时间:2013-02-11 05:51:59

标签: mysql sql group-by concat

我想对字段进行分组,但希望显示名为remain的列的所有行:

这是没有分组的当前输出:

enter image description here

并以群组输出:

enter image description here

当我分组时我想要这个:

enter image description here

这是mysql查询:

SELECT staff.name,
  staff.designation_id_designation,
  staff.status_id_status,
  Concat_Ws('=', leave_remain.leave_type_id_leave_type, leave_remain.days) AS
  remain
FROM staff INNER JOIN
  leave_remain ON staff.id_staff = leave_remain.staff_id_staff
GROUP BY staff.name    

3 个答案:

答案 0 :(得分:9)

使用GROUP_CONCAT

SELECT  staff.name,
        staff.designation_id_designation,
        staff.status_id_status,
        GROUP_CONCAT(Concat_Ws('=', leave_remain.leave_type_id_leave_type, leave_remain.days)) AS remain
FROM    staff 
        INNER JOIN leave_remain 
            ON staff.id_staff = leave_remain.staff_id_staff
GROUP   BY staff.name, staff.designation_id_designation, staff.status_id_status  

其他链接

答案 1 :(得分:1)

试试这个:

SELECT staff.name,
  staff.designation_id_designation,
  staff.status_id_status,
  GROUP_CONCAT(Concat_Ws('=', leave_remain.leave_type_id_leave_type, leave_remain.days) SEPARATOR ' ') AS remain
FROM staff INNER JOIN
  leave_remain ON staff.id_staff = leave_remain.staff_id_staff
GROUP BY staff.designation_id_designation,
         staff.name,
         staff.status_id_status;

答案 2 :(得分:1)

为此我们需要使用由''分隔的group_concat。

SELECT staff.name,
  staff.designation_id_designation,
  staff.status_id_status,
  GROUP_CONCAT(Concat_Ws('=', leave_remain.leave_type_id_leave_type, leave_remain.days) SEPARATOR ' ') AS remain
FROM staff 
INNER JOIN
  leave_remain 
ON 
staff.id_staff = leave_remain.staff_id_staff
GROUP BY staff.designation_id_designation,
         staff.name,
         staff.status_id_status;