简体   繁体   中英

how to create a foreign key where there are multipal primary key in another table

I have a table A in a database which have multiple primary keys - Primary key 1 and Primary key 2 . Now I need the create a foreign key in another table having primary key 2 as foreign key

CREATE TABLE ADMIN_INFO(
    NAME VARCHAR(20),
    EMAIL VARCHAR(20),
    PHONE_NO VARCHAR(20),
    POST VARCHAR(20),
    USER_NAME VARCHAR(16) not null ,
    PASSWORD VARCHAR(16),
    G_NAME VARCHAR(20) not null,
    PRIMARY KEY (user_name,g_name)
);
CREATE tablE Godam(
    G_NO INT PRIMARY KEY AUTO_INCREMENT,
    BILLNO VARCHAR(20),
    MARK VARCHAR(20),
    QTY INT,
    REMARK VARCHAR(10),
    G_NAME VARCHAR(20),
    FOREIGN KEY(G_NAME) REFERENCES ADMIN_INFO(G_NAME)
);

You cannot do that, as G_NAME column is not a primary key. You have created a composite key using two columns USER_NAME and G_NAME . So you need to have both columns in your second table Godam and create a foreign key using both the columns.

CREATE TABLE Godam(
    G_NO INT PRIMARY KEY AUTO_INCREMENT,
    BILLNO VARCHAR(20),
    MARK VARCHAR(20),
    QTY INT,
    REMARK VARCHAR(10),
    USER_NAME VARCHAR(16) not null ,
    G_NAME VARCHAR(20),
    FOREIGN KEY(USER_NAME, G_NAME) REFERENCES ADMIN_INFO(user_name, G_NAME)
);

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