[英]MySQL - How to get multiple rows in a single row
I'm trying to 'CONCAT' the description of multiple rows in a single row. 我正在尝试“ CONCAT”一行中多行的描述。
I have these tables: 我有这些表:
tb_employees: tb_employees:
+---------------+---------------+
| id_employee | employee |
+---------------+---------------+
| 1 | Robert Tomson |
| 2 | Jhonatan Weg |
| 3 | Eva Uhte |
+---------------+---------------+
tb_requirements: tb_requirements:
+---------------+-----------------+
| id_requirem | requirem |
+---------------+-----------------+
| 11 | Photo |
| 12 | Criminal Record |
| 13 | Shooting Test |
+---------------+-----------------+
tb_details: 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 |
+-----------------+---------------------+-------------------------+
I have to make a SELECT query
to show like this: 我必须进行
SELECT query
才能显示如下:
+-------------------------+----------------------------------------+
| employee | requirem |
+-------------------------+----------------------------------------+
| Robert Tomson | Photo - Criminal Record - Shooting Test|
| Jhonatan Weg | Photo - Shooting Test |
| Eva Uhte | Criminal Record - Shooting Test |
+-------------------------+----------------------------------------+
To be honest, i really don't know how :S 老实说,我真的不知道如何:S
Any ideas? 有任何想法吗? Thank you for answer.
谢谢你的答案。
Use GROUP_CONCAT()
使用
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
Output: 输出:
| EMPLOYEE | REQUIREMENTS | |---------------|-----------------------------------------| | Robert Tomson | Criminal Record - Photo - Shooting Test | | Jhonatan Weg | Photo - Shooting Test | | Eva Uhte | Criminal Record - Shooting Test |
Edit: 编辑:
You should use GROUP_CONCAT and GROUP BY the requirem field. 您应该使用require_字段的GROUP_CONCAT和GROUP BY。
You need to use group_concat
Try the below : 您需要使用
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 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.