我有三个表Employee,Department和一个破坏Employee和Department之间多对多关系的表。如果我想让所有员工都与他们各自的部门一起工作,那么员工就会出现重复,所以我想向所有员工展示他们的部门,但要横向展示部门以删除重复。
CREATE TABLE `tbl_emp` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
);
CREATE TABLE `tbl_dept` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
);
CREATE TABLE `tbl_emp_dept` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dep_id` bigint(20) NOT NULL DEFAULT '0',
`emp_id` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
答案 0 :(得分:1)
尝试使用GROUP_CONCAT
:
SELECT
e.id,
e.title,
GROUP_CONCAT(d.name) AS departments
FROM tbl_emp e
LEFT JOIN tbl_emp_dept ed
ON e.id = ed.emp_id
LEFT JOIN tbl_dept d
ON ed.dep_id = d.id
GROUP BY
e.id;