如何连接外键信息?

时间:2015-06-04 02:30:16

标签: mysql sql concatenation

我刚刚意识到我的措辞非常糟糕 我试图找出我是否可以在插入语句中执行此操作,而不是在尝试输出数据时

这可能听起来很混乱,但希望我能解释一下。

我有两个表,expertise(父)和department(子)

我的专业知识:

exp_id int(2) primary key 
exp_name varchar(30)

在我所在的部门:

dep_id int(2) primary key  
dep_name varchar(30)  
exp_id int(2) foreign key

我不希望部门行的结果如下所示:

dep_id dep_name exp_id

1    accounting       32
1    accounting       27
1    accounting       29

我希望它看起来像这样

dep_id dep_name      exp_id
1    accounting      32, 27, 29

因此,行中有多行,如果有意义的话。

我相信它必须与之合作,但我以前从未使用过这个并且正在寻求帮助

我刚刚意识到我的措辞非常糟糕 我试图找出我是否可以在插入语句中执行此操作,而不是在尝试输出数据时

2 个答案:

答案 0 :(得分:0)

您应该可以使用group_concat,即:

select dep_id, dep_name, group_concat(exp_id) exp_id
  from department
  group by dep_id, dep_name

您还应该考虑对您的部门表进行规范化,由于重复的dep_id, dep_name组,它目前正在违反第一范式。 reference here

修改

我看到你更新了你的问题,说你希望以这种方式在表格中存储数据,而不是显示。

答案是:你真的没有。

分隔的字段几乎不可能处理,并且在rdbms中几乎都是可怕的。如果您绝对必须以这种方式使用它,您可以使用上述查询来创建视图,并至少以正确的标准化方式存储真实数据。

重新迭代。请不要这样做。小猫会死。

答案 1 :(得分:0)

本着标准化数据的精神

-- drop table expertise
create table expertise
(   expId int not null,
    expName varchar(100) not null
);
insert expertise (expId,expName) values (32,'number massaging');
insert expertise (expId,expName) values (27,'misrepresentation');
insert expertise (expId,expName) values (29,'embezzlement');

-- select * from expertise
-- drop table department;
create table department
(   deptId int not null,
    deptName varchar(100) not null
);
insert into department (deptId,deptName) values (1,'Accounting');
insert into department (deptId,deptName) values (2,'Executive');
insert into department (deptId,deptName) values (3,'Food Service');

-- select * from department

-- drop table expDeptIntersect;
create table expDeptIntersect 
(   expId int not null,
    deptId int not null
);
insert expDeptIntersect (expId,deptId) values (27,1);
insert expDeptIntersect (expId,deptId) values (32,1);
insert expDeptIntersect (expId,deptId) values (29,1);
--select * from expdeptintersect

select d.deptId,d.deptName,group_concat(i.expId) expId
from department d
join expDeptIntersect i
on i.deptId=d.deptId
group by d.deptId,d.deptName
相关问题