繁体   English   中英

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

[英]MySQL one to many relationship add values from one table to another

我有两个表,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行绑定在一起,尽管与我尝试的第一种方法不同。 我不确定外键的设置方式是否做错了。

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

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

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

db <> fiddle演示

暂无
暂无

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

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