简体   繁体   中英

How to automatically load values from one table column to another in MYSQL

I am using Mysql 8.0 I have 2 tables given below:

Table 1:
    I_VendorID INT NOT NULL PRIMARY KEY,
    V_Code VARCHAR(50) NULL,
    V_Name VARCHAR(250) NULL,
    V_Address VARCHAR(500) NULL,
    N_Mobile NUMERIC(10, 0) NULL,
    N_Phone NUMERIC(11, 0) NULL,
    V_Email VARCHAR(100) NULL,

Table 2:
     I_POID INT NOT NULL PRIMARY KEY,
     I_VendorID INT NULL,
     V_PODetails VARCHAR(50) NULL

I wish to know if there is any way, either through query code or through mysql workbench that whatever value is in table 1 under I_VendorID is automatically copied to I_VendorID in table 2. I will always be taking the values from the user for the 2 tables at the same time. Also declared I_VendorID in table 2 as a foreign key. I thought, rather than passing values manually for I_VendorID from table 2 everytime, I could just copy the value from table 1. Is there any query or method that would automatically ensure this?

You can use mysql triggers to make sure that for each row inserted in your first table, another row is inserted in the second table

MySql documentation on triggers

CREATE TRIGGER ins_to_table_2 BEFORE INSERT ON table_1
       FOR EACH ROW
       BEGIN
           insert into table_2('I_VendorID') values(New.I_VendorID)
       END;//

I have not executed the above yet, but it's something very similar.

Truth be told though, since you will eventually add a row in the second table, you can insert it when needed and query with a left join instead of inner join so that you can return the values from the first table, even if the second one has no values yet.

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