MySQL使用子表返回每个主ID的单行,从而产生一列

时间:2018-04-25 06:40:10

标签: mysql

我试图从子表 employment_types 中获取与主表 hrms_emp_type 相关的值。子表记录可以是多个但是在获得结果时, 它应该是这样的:

salaryProcessID | description       
1360            | General
1397            | Consultant 
1557            | General, Trainee, Consultant  
1566            | General, Trainee

链接:

http://sqlfiddle.com/#!9/e1645/1

2 个答案:

答案 0 :(得分:3)

SELECT salaryProcessID, 
       GROUP_CONCAT(description ORDER BY empType SEPARATOR ', ') AS description
FROM hrms_emp_type AS spTB
JOIN employment_types AS empType ON empType.id = spTB.empType
GROUP BY salaryProcessID
ORDER BY salaryProcessID;

<强>输出

salaryProcessID description
1360            General
1397            Consultant
1557            General, Trainee, Consultant
1566            General, Trainee

<强>演示

  

http://sqlfiddle.com/#!9/e1645/24

GROUP_CONCAT()函数

  

MySQL GROUP_CONCAT()函数返回一个连接的字符串   来自组的非NULL值。

语法:

GROUP_CONCAT([DISTINCT] expr [,expr ...]
         [ORDER BY {unsigned_integer | col_name | expr}
             [ASC | DESC] [,col_name ...]]
         [SEPARATOR str_val])

答案 1 :(得分:1)

您可以使用use as below: public class Array_two { public int rows; public int cols; public int[][] values; Array_two(int rows, int cols) { this.rows = rows; this.cols = cols; values = new int[rows][cols]; } public Array_two Add(Array_two a, Array_two b) { int rsz = a.rows; int clz = a.cols; int[][] retArr = new int[rsz][clz]; for (int i = 0; i < rsz; i++) { for (int j = 0; j < clz; j++) { retArr[i][j] = a.values[i][j] + b.values[i][j]; } } Array_two ret = new Array_two(rsz, clz); ret.values = retArr; return ret; }}

GROUP_CONCAT

SQL小提琴 - http://sqlfiddle.com/#!9/e1645/16