How can I add a relationship to these two tables when there is an id and a prefix in the primary key?
P粉675258598
P粉675258598 2023-09-15 15:03:48
0
1
467

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粉675258598
P粉675258598

reply all(1)
P粉494151941

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)
  );
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!