MySQL一对多关系将值从一个表添加到另一个表

问题描述 投票:0回答:1

我有两个表,customer和CAM(客户客户经理)。 CAM具有30个唯一条目,而客户具有300个唯一条目。表应与一个CAM对许多客户具有一对多关系。

CAM的表格如下:

create table CAM(  
    CAM_ID integer auto_increment primary key,  
    First_Name varchar(20) not null,  
    Last_Name varchar(20) not null,  
    Current_Staff boolean  
);

客户表如下

create table customer(
    reference integer auto_increment primary key,
    company_name varchar(25) not null,
    address varchar(30) not null,
    town varchar(30),
    post_code varchar(10) not null,
    telephone varchar(20) not null,
    contact_fname varchar(25),
    contact_sname varchar(25),
    contact_email varchar(40)
);

CAM表是一个新表,customer表已经存在。我通过两个不同的语句将CAM_ID列添加到客户表中:1

alter table customer
add CAM_ID int

2

alter table customer
add foreign key (CAM_ID) references CAM(CAM_ID)

[当尝试将它们作为一个查询运行时失败。

我需要一些有关如何使用CAM表中的值填充客户表中CAM_ID列的建议。我尝试了一些最终不起作用的方法。例如,我试图将CAM_ID都绑定到参考值,但是这仅填充了前30行。另外,我尝试对CAM_ID和参考中的值进行一些数学运算,以将它们绑定在一起。再次,这只将30行绑定在一起,尽管与我尝试的第一种方法不同。我不确定外键的设置方式是否做错了。

mysql one-to-many
1个回答
-1
投票

[当尝试将它们作为一个查询运行时失败。

组合这两个DDL的正确方法:

alter table customer
add (CAM_ID int,
 foreign key (CAM_ID) references CAM(CAM_ID)
)

db<>fiddle demo

© www.soinside.com 2019 - 2024. All rights reserved.