search

Home  >  Q&A  >  body text

How can I add a relationship to these two tables when there is an id and a prefix in the primary key?

I don't know how to link these two tables. Can anyone help? I want to add a relationship in these two tables but since I am using id and prefix as primary key it is not accepting it as foreign key. I keep getting "Foreign key constraint is malformed".

CREATE TABLE Donor (
    id int(3) ZEROFILL NOT NULL AUTO_INCREMENT,
    prefix varchar(5) NOT NULL DEFAULT 'D',
    name varchar(50) NOT NULL,
    PRIMARY KEY (id, prefix)
  );
    
INSERT INTO Donor (name) VALUES
('Product #1'),
('Product #2');

SELECT CONCAT(prefix,id) as "DonorID", name FROM Donor;

CREATE TABLE Blood_Type (
    btid int(3) ZEROFILL NOT NULL AUTO_INCREMENT,
    btprefix varchar(5) NOT NULL DEFAULT 'BT',
    id int(3) NOT NULL,
    prefix varchar(5) NOT NULL DEFAULT 'D',
    name varchar(50) NOT NULL,
    PRIMARY KEY (btid, btprefix),
    foreign key (id, prefix) references Donor(id, prefix)
  );
    
INSERT INTO Blood_Type (name) VALUES
('Blood #1'),
('Blood #2');

SELECT CONCAT(btprefix, btid) as "bloodID", name FROM Blood_Type;

P粉675258598P粉675258598443 days ago534

reply all(1)I'll reply

  • P粉494151941

    P粉4941519412023-09-16 09:31:19

    Add ZEROFILL to your ID:

    CREATE TABLE Blood_Type (
        btid int(3) ZEROFILL NOT NULL AUTO_INCREMENT,
        btprefix varchar(5) NOT NULL DEFAULT 'BT',
        id int(3) ZEROFILL NOT NULL,
        prefix varchar(5) NOT NULL DEFAULT 'D',
        name varchar(50) NOT NULL,
        PRIMARY KEY (btid, btprefix),
        foreign key  (id, prefix) references Donor(id, prefix)
      );

    reply
    0
  • Cancelreply