How to specify the constraint with 2 tables - mysql

I have the following 3 tables
CREATE TABLE BUBBLES_CSC (
CSC_ID integer UNSIGNED NOT NULL AUTO_INCREMENT,
COUNTRY_NAME varchar(255) NOT NULL,
STATE_NAME varchar(255) NOT NULL,
CITY_NAME varchar(255) NOT NULL,
PRIMARY KEY(CSC_ID,STATE_NAME,CITY_NAME),
INDEX(CSC_ID ,CITY_NAME,COUNTRY_NAME )
);
CREATE TABLE BUBBLES_REGION (
REGION_ID integer UNSIGNED NOT NULL AUTO_INCREMENT,
REGION_NAME varchar(255) NOT NULL,
CSC_ID integer UNSIGNED NOT NULL,
PRIMARY KEY(REGION_ID),
FOREIGN KEY (CSC_ID) REFERENCES BUBBLES_CSC(CSC_ID) ON UPDATE CASCADE ON DELETE CASCADE,
INDEX(REGION_ID ,REGION_NAME ,CSC_ID )
);
CREATE TABLE BUBBLES_HOTEL (
HOTEL_ID integer UNSIGNED NOT NULL AUTO_INCREMENT,
NAME varchar(255) NOT NULL,
DESCRIPTION varchar(255) DEFAULT "No description",
CSC_ID integer UNSIGNED NOT NULL,
REGION_ID integer UNSIGNED NOT NULL,
STREET_ADDRESS varchar(255) DEFAULT NULL,
PRIMARY KEY(HOTEL_ID),
FOREIGN KEY (CSC_ID) REFERENCES BUBBLES_CSC(CSC_ID) ON UPDATE CASCADE,
FOREIGN KEY (REGION_ID) REFERENCES BUBBLES_REGION(REGION_ID) ON UPDATE CASCADE,
INDEX(HOTEL_ID,NAME,CSC_ID,REGION_ID)
)CHARACTER SET=utf8;
Now i know how to do a foreign key, But how to specify that the CSC_ID in BUBBLES_HOTEL should be same as the CSC_ID specified in BUBBLES_REGION for the row pointed to by REGION_ID in BUBBLES_HOTEL

The proper way to do this is not to have the column CSC_ID in BUBBLES_HOTEL at all. Each row in BUBBLES_HOTEL contains a link to a row in BUBBLES_REGION, which in turn contains a link to a row in BUBBLES_CSC. That's how you identify to which row in BUBBLES_CSC a given row in BUBBLES_HOTEL corresponds. Your current design is not normalised.
Having said that, you could achieve what you ask by replacing the two foreign keys on BUBBLES_HOTEL with just one:
FOREIGN KEY (CSC_ID, REGION_ID) REFERENCES BUBBLES_REGION (CSC_ID, REGION_ID)

I assume that all three relations create one-to-one-to-one chain. If so, you should not have the CSC_ID column in BUBBLES_HOTEL, it is redundant: you always can get it via BUBBLES_REGION.

Related

Single attribute used as a foriegn key for multiple tables

I want to make Emp_id as a foreign key for Employee table and Record table. Can this be done?
This is my code
CREATE TABLE Empolyee(
EID varchar(8) NOT NULL,
E_name varchar(30) NOT NULL,
NID varchar(30) NOT NULL,
sex varchar(40) NOT NULL,
history varchar(30) NOT NULL,
salary varchar(10) NOT NULL,
cid int NOT NULL,
FOREIGN KEY (cid) REFERENCES Employee_Contact_No(CID),
FOREIGN KEY (cid) REFERENCES Employee_email(Email_ID),
PRIMARY KEY (EID)
);
Receptionist table
CREATE TABLE Receptionist(
r_id varchar(8) NOT NULL,
Emp_ID varchar(8) NOT NULL,
PRIMARY KEY (r_id),
FOREIGN KEY (Emp_ID) REFERENCES Employee(EID),
FOREIGN KEY (Emp_ID) REFERENCES Record(EID)
);
And the receptionist's records
CREATE TABLE Record(
record_no varchar(8) NOT NULL,
EID VARCHAR(8) Not Null,
patient_id varchar(15) NOT NULL,
discription varchar(30) NOT NULL,
appointment varchar(40) NOT NULL,
PRIMARY KEY (record_no)
);
You can make a single field reference multiple tables, but I cannot think of a scenario where it would ever be a good idea; it would require both tables to have the same id value, and (at least imply) that those id values be meaningfully coordinated.
From the looks of your examples, it is probably more likely that you need tables like Employee_Contact_No and Employee_email to reference the Employee table.

trying to relate two table together

so pretty new to SQL I created 2 tables which I wanted to be related to one another but I'm getting an error "#1215 - Cannot add foreign key constraint" can someone point me to the right direction of this problem?
CREATE TABLE movie(
id INT(1) NOT NULL AUTO_INCREMENT,
nearname VARCHAR(25) NOT NULL,
release_date DATE NOT NULL,
lang VARCHAR(10) NOT NULL,
PRIMARY KEY(id),
CONSTRAINT same_movie FOREIGN KEY(id) REFERENCES movie_cast(movie_id)
);
CREATE TABLE movie_cast(
movie_id INT(1) NOT NULL AUTO_INCREMENT,
director_name VARCHAR(20) NOT NULL,
actor_name VARCHAR(20) NOT NULL,
actress_name VARCHAR(20) NOT NULL,
PRIMARY KEY(movie_id),
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie(id)
);
You need to refer to the same column name as the primary key. In this case, it is called id:
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie_cast(id)
Of course, your DDL doesn't define movie_cast. So, I am guessing the second table should be something like:
CREATE TABLE movie_cast (
id INT NOT NULL AUTO_INCREMENT,
movie_id int not null,
cast_name varchar(255)
PRIMARY KEY(id),
CONSTRAINT fk_movie_cast_movie FOREIGN KEY(movie_id) REFERENCES movie(movie_id)
);

MySQL Error 1215 creating foreign key

My question is about MySQL, I keep getting an error (Error 1215: Cannot add Foreign key Constraint) while trying to forward engineer a schema to a db server, I've got two parent tables:
CREATE TABLE IF NOT EXISTS alunos (
idAluno INT NOT NULL AUTO_INCREMENT,
NomeAluno VARCHAR(100) NOT NULL,
nifAluno VARCHAR(15) NOT NULL,
moradaAluno VARCHAR(255) NOT NULL,
telefoneAluno VARCHAR(9) NOT NULL,
emailAluno VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
PRIMARY KEY(idAluno, nifAluno)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS cursos (
idCurso INT NOT NULL AUTO_INCREMENT,
nomeCurso VARCHAR(50) NOT NULL,
horas INT NOT NULL,
PRIMARY KEY(idCurso, nomeCurso)
) ENGINE=INNODB;
And this is my child table:
CREATE TABLE IF NOT EXISTS inscritos (
id INT NOT NULL AUTO_INCREMENT,
Nome VARCHAR(100) NOT NULL,
Morada VARCHAR(255) NOT NULL,
Naturalidade VARCHAR(45) NOT NULL,
NIF VARCHAR(15) NOT NULL,
email VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
Telefone VARCHAR(9) NOT NULL,
Curso VARCHAR(50) NOT NULL,
Horas INT NOT NULL,
Inicio DATE NOT NULL,
Validade DATE NOT NULL,
Atividade VARCHAR(45) NOT NULL,
PRIMARY KEY(id),
INDEX(NIF),
INDEX(Curso),
FOREIGN KEY(NIF)
REFERENCES alunos(nifAluno)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY(Curso)
REFERENCES cursos(nomeCurso)
ON UPDATE RESTRICT ON DELETE RESTRICT
) ENGINE=INNODB;
I've looked through the code over and over and I can't seem to find the error when assigning the foreign keys.
Thanks in advance.
Because, NIF and Curso aren't primary/unique key in inscritos table. Creating index doesn't mean you are creating key on same column. So, just for your information. The referenced columns in the Parent table must be the left-most columns of a key. Best if the key is PRIMARY KEY or UNIQUE KEY.
As #Bill commented, he has an answer where he has prepared a checklist, you may refer to make sure, you won't get any other error.

Cannot add or update a child row: foreign key constraint fails

Hi I am wondering why I getting an error
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (exams.entries, CONSTRAINT entries_ibfk_2
FOREIGN KEY (student_id) REFERENCES students (student_id))
Any help would be appriatiated!
Here are the scripts that I think are relevant to the problem I'm having,
First I made this table entries and everything was fine
CREATE TABLE entries(
subject_id INT UNSIGNED NOT NULL,
subject_name VARCHAR(60) NOT NULL,
level_of_entry VARCHAR(60) NOT NULL,
exam_board VARCHAR(60) NOT NULL,
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (date_of_exam),
FOREIGN KEY (subject_id)
REFERENCES subjects(subject_id),
FOREIGN KEY (student_id)
REFERENCES students(student_id)
Then I tried to insert data and I got the error.
INSERT INTO entries (subject_id,subject_name, level_of_entry, exam_board,date_of_exam)
VALUE ('1','chemistry','as','ocr','2017-05-05 12:00:00'),
('2','biology','gcse','aqa','2017-05-05 12:00:01'),
('3','music','gcse','edexcel','2017-05-05 12:00:02'),
('4','english','a','ocr','2017-05-05 12:00:03'),
('5','physics','a','aqa','2017-05-05 12:00:04'),
('6','maths','gcse','aqa','2017-05-05 12:00:05'),
('7','computing','gcse','aqa','2017-05-05 12:00:06'),
('8','physical_education','gcse','aqa','2017-05-05 12:00:07'),
('9','design_and_technology','gcse','aqa','2017-05-05 12:00:08'),
('10','french','gcse','aqa','2017-05-05 12:00:09');
It suggest on other questions similar to this to make sure your parent table has the same values but it does and its making know sense to me.
Here is the parent script.
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id) ,
UNIQUE (email));
Here is the other parent script but I'm having no problems with it.
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(60) NOT NULL,
level_of_entry VARCHAR(60) NOT NULL,
exam_board VARCHAR(60) NOT NULL,
PRIMARY KEY (subject_id) ,
UNIQUE (subject_id));
If anyone could help I would be extremely grateful!
There are two issues with your logic related to student_id.
You should not have AUTO_INCREMENT in foreign key table.
A table which has a foreign key can't auto-populate values (logically and technically). It has to refer to some value in its Primary table. In your case, it is students table.
So, change your table structure as below:
CREATE TABLE entries(
subject_id INT UNSIGNED NOT NULL,
subject_name VARCHAR(60) NOT NULL,
level_of_entry VARCHAR(60) NOT NULL,
exam_board VARCHAR(60) NOT NULL,
student_id INT UNSIGNED NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (date_of_exam),
FOREIGN KEY (subject_id)
REFERENCES subjects(subject_id),
FOREIGN KEY (student_id)
REFERENCES students(student_id)
You should specify a value in your INSERT query for entries table
You need to ensure you insert a value manually in your entries table for student_id column.
A side not as specified in comments that you defined subject_id as INT but you are trying to insert character values.
Change your insert query as below:
INSERT INTO entries (subject_id,subject_name, level_of_entry, exam_board,date_of_exam, student_id)
VALUE (1,'chemistry','as','ocr','2017-05-05 12:00:00', 100),
(2,'biology','gcse','aqa','2017-05-05 12:00:01', 101);
Note: I assumed 100 and 101 as your existing student ids from students table. You need to replace them with the correct ids from your table.

How do I create this relational table?

Below is a portion of relational data base. I know how to create table Film and assign primary key to it.. but don't understate creating other tables and assigning primary key to it.
Any help?
table Film
CREATE TABLE Film (
Id INTEGER PRIMARY KEY,
Title VARCHAR(35) NOT NULL,
Description VARCHAR(256) NOT NULL,
Year INTEGER NOT NULL CHECK (Year > 1900),
Rating INTEGER NOT NULL DEFAULT 3 CHECK (Rating BETWEEN 1 AND 5)
);
how do I create table FilmFormat and OrderItem ?
CREATE TABLE `jy` (
`PKfield` INTEGER UNSIGNED NOT NULL DEFAULT NULL AUTO_INCREMENT,
`field2` VARCHAR(45) NOT NULL,
PRIMARY KEY (`PKfield`),
CONSTRAINT `FK` FOREIGN KEY `FK` (`PKfield`)
REFERENCES `Film` (`Id`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
This is enough to show you how to create a foreign key constraint between the two tables. As commented, the CHECK constraint will be parsed but ignored.
CREATE TABLE Film (
Id INTEGER PRIMARY KEY,
Title VARCHAR(35) NOT NULL,
Description VARCHAR(256) NOT NULL,
Year INTEGER NOT NULL CHECK (Year > 1900),
Rating INTEGER NOT NULL DEFAULT 3 CHECK (Rating BETWEEN 1 AND 5)
);
CREATE TABLE FilmFormat (
FilmId INTEGER not null,
FormatId INTEGER not null,
Price decimal(16,4) null,
Primary Key(FilmId, FormatId),
Constraint FK_FilmFormat_FilmId FOREIGN KEY (FilmId) REFERENCES Film(Id)
);
Doing the last table will just be doing your work for you.