[英]How to use Union using Inner Join
I have a one to many relationship between departments
and users
. 我在
departments
和users
之间有一对多的关系。
Database Design: 数据库设计:
users
has each own department and department has many users
. users
有自己的部门,部门有很多users
。 I wanted to select all the department_name
but I have a duplicate values of department_name
I want to merge it into one so I planned to use UNION how can I implement this using Inner Join? 我想选择所有
department_name
但是我有一个重复的department_name
值,我想将其合并为一个值,因此我计划使用UNION,如何使用内部联接实现此功能? This is my code so far. 到目前为止,这是我的代码。
SQL 的SQL
SELECT D.department_name FROM users U
INNER JOIN departments D ON D.id = U.department_id;
Results: 结果:
If you want only the distinct department names, you need to group the users into a comma separated values. 如果只需要不同的部门名称,则需要将用户分组为逗号分隔的值。
select d.department_name, group_concat(u.id) user_id_list
from departments d inner join users u on d.department_id = u.department_id
group by d.department_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.