我正试图'CONCAT'在一行中描述多行。
我有这些表格:
tb_employees:
+---------------+---------------+
| id_employee | employee |
+---------------+---------------+
| 1 | Robert Tomson |
| 2 | Jhonatan Weg |
| 3 | Eva Uhte |
+---------------+---------------+
tb_requirements:
+---------------+-----------------+
| id_requirem | requirem |
+---------------+-----------------+
| 11 | Photo |
| 12 | Criminal Record |
| 13 | Shooting Test |
+---------------+-----------------+
tb_details:
+-----------------+---------------------+-------------------------+
| id_detail | id_employee | id_requirem |
+-----------------+---------------------+-------------------------+
| 1 | 1 | 11 |
| 2 | 1 | 12 |
| 3 | 1 | 13 |
| 4 | 2 | 11 |
| 5 | 2 | 13 |
| 6 | 3 | 12 |
| 7 | 3 | 13 |
+-----------------+---------------------+-------------------------+
我必须让SELECT query
显示如下:
+-------------------------+----------------------------------------+
| employee | requirem |
+-------------------------+----------------------------------------+
| Robert Tomson | Photo - Criminal Record - Shooting Test|
| Jhonatan Weg | Photo - Shooting Test |
| Eva Uhte | Criminal Record - Shooting Test |
+-------------------------+----------------------------------------+
说实话,我真的不知道如何:S
有什么想法吗?谢谢你的回答。
答案 0 :(得分:1)
使用GROUP_CONCAT()
SELECT e.employee, GROUP_CONCAT(r.requirem ORDER BY r.requirem SEPARATOR ' - ') requirements
FROM tb_employees e LEFT JOIN tb_details d
ON e.id_employee = d.id_employee JOIN tb_requirements r
ON d.id_requirem = r.id_requirem
GROUP BY e.id_employee, e.employee
输出:
| EMPLOYEE | REQUIREMENTS | |---------------|-----------------------------------------| | Robert Tomson | Criminal Record - Photo - Shooting Test | | Jhonatan Weg | Photo - Shooting Test | | Eva Uhte | Criminal Record - Shooting Test |
这是 SQLFiddle 演示
答案 1 :(得分:0)
编辑:
您应该使用GROUP_CONCAT和GROUP BY requirem字段。
答案 2 :(得分:0)
您需要使用group_concat
尝试以下内容:
SELECT group_concat(distinct(e.employee) separator ', ') , group_concat(r.requirem separator ', ')
FROM TB_DETAILS d
JOIN TB_EMPLOYEES e ON d.id_employee = e.id_employee
JOIN tb_requirements r ON d.id_requirem = r.id_requirem
| GROUP_CONCAT(DISTINCT(E.EMPLOYEE) SEPARATOR ', ') | GROUP_CONCAT(R.REQUIREM SEPARATOR ', ') |
|---------------------------------------------------|------------------------------------------|
| Robert Tomson, Jhonatan Weg, Eva Uhte | Photo, Criminal Record, Shooting Test, |
| | Photo, Shooting Test, Criminal Record, |
| | Shooting Test |