composite foreign key add fails - mysql

I have got 4 tables here:
CREATE TABLE paper (
id VARCHAR(20) PRIMARY KEY,
name VARCHAR(30)
) ENGINE =INNODB;
CREATE TABLE subscriber (
id VARCHAR(10) PRIMARY KEY,
name VARCHAR(20),
address VARCHAR(30),
suburb VARCHAR(20),
state VARCHAR(3),
postcode VARCHAR(4))
round_id INTEGER NOT NULL,
FOREIGN KEY (round_id) REFERENCES round (id)
ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE = INNODB;
CREATE TABLE current_order (
paper_id VARCHAR(20),
subscriber_id VARCHAR(10),
PRIMARY KEY (paper_id, subscriber_id),
FOREIGN KEY (paper_id) REFERENCES paper (id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY(subscriber_id) REFERENCES subscriber (id)
ON UPDATE CASCADE ON DELETE RESTRICT)
ENGINE = INNODB;
CREATE TABLE receipt (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
receipt_date DATE,
paid_till_date DATE,
paper_id VARCHAR(20),
subscriber_id VARCHAR(10))
ENGINE = INNODB;
Now table paper has a primary key ID, it is referenced by paper_id in table current_order.
Table subscriber has a primary key ID, it is referenced by subscriber_id in table current_order.
Tabe current_order has a composite primary key (paper_id,subscriber_id).
So these three table has been linked together through the foreign key relationship.
If I want to have the last table receipt linked with these three table, how do I do that? My idea was to
1:set a compound foreign key (paper_id,subscriber_id) referencing to the compound primary key (paper_id,subscriber_id) in table current_order.
2:set two single foreign key (paper_id) and (subscriber_id) referencing to (paper_id) and )subscriber_id) in table current_order separately.
Neither method worked and it came up with error 1452:cannot add or update child row.
So I am really desperate to know what is the proper way to set relationship between table receipt and table current_order?
here is the E-R Digram:
E-R DIGRAM
There is two links between table receipt and table current_order and I am required to set relationship according to that.

i'm not a mysql expert but i would try this:
CREATE TABLE receipt (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
receipt_date DATE,
paid_till_date DATE,
paper_id VARCHAR(20),
subscriber_id VARCHAR(10),
FOREIGN KEY (paper_id,subscriber_id) REFERENCES current_order (paper_id,subscriber_id)
ON UPDATE CASCADE ON DELETE RESTRICT)
ENGINE = INNODB;
does it works?

Related

How to reference foreign key in mysql at phpmyadmin

I am using mysql in phpmyadmin. I have created two tables.
company (
company_id INT PRIMARY KEY,
company_name VARCHAR(20)
);
users (
user_id INT PRIMARY KEY,
user_first_name VARCHAR(20) ,
user_last_name VARCHAR(20),
user_type VARCHAR(10),
user_email VARCHAR(40)
);
Now i want to declare Foreign key company(company) reference to users(user_id). SO company will be primary and foreign key at same time. How do i Do that?
You're looking to add the following to the users table:
FOREIGN KEY (company) REFERENCES company(company_id)
Which will create a new key in that table called company, which references the company_id of the company table.
ALTER TABLE company ADD CONSTRAINT company_id_fk FOREIGN KEY (company_id) REFERENCES users(user_id) ON DELETE RESTRICT ON UPDATE RESTRICT;

How to add on delete cascade option in mysql?

I created two tables students and orders and I added a foreign key constraint to the order table but I forgot to add on delete cascade option to this table.
table STUDENTS:
CREATE TABLE STUDENTS (
ID varchar(50) NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
)
Table ORDERS
CREATE TABLE Orders
(O_Id int NOT NULL PRIMAY KEY,
Order_No int NOT NULL,ID varchar(50))
Add foreign key to "orders":
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY(ID)
REFERENCES STUDENTS (ID)
I tried this attempt :
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY(ID)
REFERENCES STUDENTS (ID) ON DELETE CASCADE
Thanks.
You have a typo in the Order table. You have PRIMAY where it should be PRIMARY.
After correcting this, I tried creating the tables and all statements worked fine, including the last one.

MySQL, MariaDB: Cannot create a table - ERROR 1005 (HY000). Something wrong with foreign key

I am new to databases and I keep getting an error when I try to create these tables. Where is a mistake?
I have found loads of questions similar to mine, but they didn't help me to resolve this problem.
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (course_name) REFERENCES course (course_name)
);
This is from INNODB STATUS.
LATEST FOREIGN KEY ERROR
------------------------
130603 20:17:22 Error in foreign key constraint of table testdb/students_marks:
FOREIGN KEY (course_name) REFERENCES course (course_name)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Your primary key is set to cou_id and course_name in your course table. To add a foreign key constraint in your students_marks table, you'd have to reference both fields (and include both fields in your table definition):
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
cou_id VARCHAR(3),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (cou_id,course_name) REFERENCES course(cou_id,course_name)
);
SQL Fiddle Demo
You are referencing only one field of a composed primary key!

creating foreign key for primary key that's already in use

So, this is my input, I'm designing a hospital database and I'm creating a table that will hold the relationships between the patients in the 'patients' table and the rooms in the 'room' table (clever, I know).
here's the statement is used to declare both tables:
create table patient_room
(
pr_id int NOT NULL PRIMARY KEY auto_increment,
patient_id int NOT NULL,
room_id int NOT NULL,
)ENGINE = InnoDB;
create table patients
(
patient_id int primary key not null auto_increment,
fname varchar(30),
lname varchar(30),
suffix enum('I','II','III','IV','JR','SR'),
sex enum('M','F','U','T'),
eye_color enum('BK','BR','BL','GY','GR','HZ','MN','DX','UN'),
hair_color enum('BK','BR','BN','RD','WH','SN','BD','UN'),
date_of_birth date not null,
height int unsigned not null,
weight int unsigned not null,
admitted datetime not null
) Engine = InnoDB;
here's my alter statement
alter table patient_room add foreign key (patient_id) references patient(patient_id) on delete cascade on update cascade;
I get the return:
ERROR 1005 (HY000): Can't create table 'Mthomas.#sql-3dac_5f1' (errno: 150)
I was able to alter the table to create a foreign key using
alter table patient_room add foreign key (room_id) references room(room_id) on delete cascade on update cascade;
without error. I do have have patient_id as a foreign key already on another patient_meds table, and I'm thinking that could be the issue... if so? How do I mitigate it?
your table is called patients and not patient. You need to change
alter table patient_room add foreign key (patient_id) references patient(patient_id) on delete cascade on update cascade;
to
alter table patient_room add foreign key (patient_id) references patients(patient_id) on delete cascade on update cascade;
^

mysql foreign key reference from a composite key

I am creating an application that will handle and record when a student gets advised by a faculty member at a university and I need an effective way to structure the tables. My problem is coming from a lack of referential integrity, caused by the inability to create a foreign key that will reference a STUDENT on only part of a composite key in ADVISE_HIST which is (STUDENT_ID,DATE_ADVISED)
here are some of the tables
create table STUDENT(
LNAME varchar(50),
FNAME varchar(50),
ID char(9) primary key,
ASSIGNED_ADVISOR_EMAIL varchar(70),
foreign key (ASSIGNED_ADVISOR_EMAIL) references DEP_FACULTY(EMAIL) ON DELETE SET NULL,
IS_ADVISED tinyint(1),
);
create table DEP_FACULTY(
LNAME varchar(50),
FNAME varchar(50),
EMAIL varchar(70) primary key
);
create table ADVISE_HIST(
STUDENT_ID char(9),
/*foreign key (STUDENT_ID) references STUDENT(ID),*/
ACTUAL_ADVISOR_EMAIL char(70) NOT NULL,
foreign key (ACTUAL_ADVISOR_EMAIL) references DEP_FACULTY(EMAIL),
DATE_ADVISED date,
primary key REF_ADVISE_HIST (STUDENT_ID, DATE_ADVISED),
);
My question is, is there a way around not being able to create this key or is there a better structure that I'm not thinking of?
MySQL has a lot of restrictions on foreign keys. Among the ones that might be getting in your way . . .
Both tables have to use the INNODB engine.
"In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. "
This code works in my version (5.1.62).
create table DEP_FACULTY(
LNAME varchar(50),
FNAME varchar(50),
EMAIL varchar(70) primary key
) ENGINE = INNODB;
insert into DEP_FACULTY values ('Gregor', 'Brandich', 'gbrandich#thisdomain.com');
create table STUDENT(
LNAME varchar(50),
FNAME varchar(50),
ID char(9) primary key,
ASSIGNED_ADVISOR_EMAIL varchar(70),
foreign key (ASSIGNED_ADVISOR_EMAIL) references DEP_FACULTY(EMAIL) ON DELETE SET NULL,
IS_ADVISED tinyint(1)
) ENGINE = INNODB;
insert into STUDENT values ('Charmaine', 'DePeletier', 'cmd', 'gbrandich#thisdomain.com', 1);
create table ADVISE_HIST(
STUDENT_ID char(9),
foreign key (STUDENT_ID) references STUDENT(ID),
ACTUAL_ADVISOR_EMAIL char(70) NOT NULL,
foreign key (ACTUAL_ADVISOR_EMAIL) references DEP_FACULTY(EMAIL),
DATE_ADVISED date,
primary key REF_ADVISE_HIST (STUDENT_ID, DATE_ADVISED)
) ENGINE = INNODB;
insert into ADVISE_HIST values ('cmd', 'gbrandich#thisdomain.com', CURRENT_DATE);
insert into ADVISE_HIST values ('ctd', 'gbrandich#thisdomain.com', CURRENT_DATE);
Of those last two inserts, the first works. The second should throw a foreign key constraint error.