简体   繁体   中英

MySQL one to many relationship add values from one table to another

I have two tables, customer and CAM (customer account manager). CAM has 30 unique entries and customer has 300. The tables should have a one to many relationship with one CAM to many customers.

The table for CAM is as follows:

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

The table for customer is as follows

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

The CAM table is a new table, the customer table was pre-existing. I added in the CAM_ID column to the customer table through two different statements:
1

alter table customer
add CAM_ID int

2

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

When trying to run them as one query it was failing.

I need some advice on how to populate the CAM_ID column within the customer table with the values from the CAM table. I've tried some methods that ultimately didn't work. For example, I was trying to tie both the CAM_ID to the reference value, however this only populated the first 30 rows. Additionally, I tried to do some math with the values in both CAM_ID and reference to try a tie them together. Again this only tied 30 rows together, though in a different way to the first method I tried. I'm not sure if I've done something wrong with the way the foreign key has been setup.

When trying to run them as one query it was failing.

Proper way of combining these two DDLs:

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

db<>fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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