简体   繁体   English

如何连接两个具有一对多关系的表?

[英]How to join two tables having one to many relationship?

I've one user table and another user_project table which contains primary key of user as its foreign key and user can have one or more projects. 我有一个用户表和另一个user_project表,其中包含用户的主键作为其外键,用户可以有一个或多个项目。 I need to join these tables to get comma separated project names for particular user. 我需要连接这些表以获取特定用户的逗号分隔项目名称。

I've tried something like this - 我尝试过这样的事情 -

select group_concat(epi.project_name)
from user u
     inner join employee_projects_info epi on epi.employee_id= u.id
group by epi.project_name

but it is not giving me list of projects user wise. 但它没有给我用户明智的项目列表。

remove epi.project_name from group by , add epi.employee_id in group by group by删除epi.project_namegroup by中添加epi.employee_id

select epi.employee_id,group_concat(epi.project_name) 
from user u inner join employee_projects_info epi 
on epi.employee_id= u.id 
group by epi.employee_id

make group by id and concat all project name: 按ID生成组并连接所有项目名称:

 select epi.employee_id, group_concat(epi.project_name)
from user u    inner join employee_projects_info epi on epi.employee_id= u.id
group by epi.employee_id

First, try to get all the users along with their projects. 首先,尝试让所有用户和他们的项目一起。 You can get that data by 您可以通过获取该数据

select u.id,epi.id,epi.project_name
from users u
inner join employee_projects_info epi on epi.employee_id = u.id

To get the comma separated project names for every user, you'll have to use group by in the above query. 要为每个用户获取逗号分隔的项目名称,您必须在上面的查询中使用group by You can find that query in other people's answers. 您可以在其他人的答案中找到该查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM