【问题标题】:How do i concatenate information from a foreign key?如何连接来自外键的信息?
【发布时间】:2015-06-04 02:30:16
【问题描述】:

我才意识到我的措辞很糟糕 我正在尝试确定是否可以在插入语句中执行此操作,而不是在尝试输出数据时

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

我有两个表,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

所以一行中有多行,如果这有意义的话。

我相信我必须使用它的串联,但我以前从未使用过它并且正在寻求帮助

我才意识到我的措辞很糟糕 我正在尝试确定是否可以在插入语句中执行此操作,而不是在尝试输出数据时

【问题讨论】:

  • 什么在什么表中。比如什么是32,一个id?什么是 1
  • dept 似乎既是实体又是相交表。归一化不好?
  • 你真的希望你的部门表看起来像那样。在 rdbms 中的几乎每一种情况下,分隔字段都是一个糟糕的主意。

标签: mysql sql concatenation


【解决方案1】:

你应该可以使用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 中到处都是可怕的。如果您绝对必须采用这种方式,则可以使用上述查询来创建视图,并至少以适当的规范化方式存储真实数据。

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

【讨论】:

  • 同意。他们会慢慢来的。
【解决方案2】:

本着规范化数据的精神

-- 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2021-12-27
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多