I am trying to add a foreign key constraint, but it fails. I did that many times before and I can not determine why it is doing that. Basically, I want to relate Skills and Employees to the Skill_Bridge table. I was able to relate Skills with the Skill_Bridge, however when I try to do the same with Employees it fails. The data types are the same, so I do not think this is the problem. I also tried to creating a primary key for the Skill_Bridge, and then try to relate them and it did not work as well. The first constraint is the one that fails 'FKey1'. This is my code. Any help will be appreciated. Thanks in advance.
create database if not exists Q3;
use Q3;
drop table if exists Employees;
create table Employees(
employeekey int not null,
firstName varchar (100) not null,
lastName varchar (100) not null,
employeeSkillGroupkey int not null,
primary key (employeekey) );
insert into Employees values
(1, 'Ted', 'Codd', 1),
(2, 'Ralph' ,'Kimball', 7),
(3, 'Joe' ,'Celko', 1),
(4, 'James' ,'Gosling', 2),
(5, 'Godfrey', 'Muganda', 6),
(6, 'Margy', 'Ross', 5),
(7, 'Peter', 'Chen', 4),
(8, 'Terry' ,'Halpin',3),
(9, 'Tony', 'Morgan', 2);
drop table if exists Skills;
create table Skills(
empSkillKey int not null,
empSkillDescription varchar (1000) not null,
empSkillCategory varchar (200) not null,
primary key (empSkillkey));
insert into Skills values
(1, 'SQL', 'Database'),
(2, 'ERD', 'Database'),
(3, 'DM', 'Database'),
(4, 'Java', 'Programming'),
(5, 'Pascal', 'Programming');
drop table if exists Skill_Bridge;
create table Skill_Bridge(
employeeSkillGroupkey int not null,
empSkillKey int not null
);
insert into Skill_Bridge values
( 1, 1),
( 2, 4),
( 3, 4),
( 3, 5),
( 4, 4),
( 4, 2),
( 5, 1),
( 5, 3),
( 6, 4),
( 6, 5),
( 6, 2),
( 7, 1),
( 7, 2),
( 7, 3),
( 7, 4);
ALTER TABLE Employees ADD CONSTRAINT FKey1 FOREIGN KEY (employeeSkillGroupkey)
REFERENCES Skill_Bridge (employeeSkillGroupkey)
ON DELETE Restrict
ON UPDATE Cascade;
ALTER TABLE Skill_Bridge ADD CONSTRAINT ForK2 FOREIGN KEY (empSkillKey)
REFERENCES Skills (empSkillKey)
ON DELETE Restrict
ON UPDATE Cascade;
You need to create an index on employeeSkillGroupkey in skill_bridge table before you can reference it in a foreign key, see mysql documentation on foregn keys:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
You may also want to reverse the direction of the foreign key. The connection table should reference the master table, not vice versa.
Related
I am working on a personal project and I don't know how to create a dynamic query with MySQL. I would like to get all version of a file stored in a database. For this purpose I replaced file by simplest name "first" in a test database created with this script:
/*
DROP DATABASE IF EXISTS request_test;
CREATE DATABASE IF NOT EXISTS request_test
DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE request_test;
*/
DROP TABLE IF EXISTS first_next;
CREATE TABLE first_next(
id INT(3) UNSIGNED ,
first VARCHAR(40) NOT NULL,
ik_next INT(3) NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE first_next ADD PRIMARY KEY (`id`);
ALTER TABLE first_next MODIFY `id` INT(3) NOT NULL AUTO_INCREMENT;
ALTER TABLE first_next ADD CONSTRAINT fn1 FOREIGN KEY (ik_next) REFERENCES first_next(id);
Sample data:
INSERT INTO first_next (id, first, ik_next)
VALUES
(1, 'toto1', NULL),
(2, 'titi1', NULL),
(3, 'riri1', NULL),
(4, 'titi2', 2),
(5, 'fifi1', NULL),
(6, 'toto2', 1),
(7, 'titi3', 4),
(8, 'fifi2', 5),
(9, 'fifi3', 8),
(10, 'toto3', 6),
(11, 'loulou1', NULL),
(12, 'toto4', 10);
As you can see toto1 is replaced by successively 3 other name toto2, toto3 and toto4. With the following query I get the full history of toto1:
SELECT first.id,first.first AS initiale,
second.id,second.first AS suivante_1,
third.id,third.first AS suivante_2,
fourth.id,fourth.first AS suivante_3
FROM first_next AS first
INNER JOIN first_next AS second
ON second.ik_next = first.id
INNER JOIN first_next AS third
ON third.ik_next = second.id
INNER JOIN first_next AS fourth
ON fourth.ik_next = third.id
WHERE fourth.id = 12
ORDER BY first.id ASC;
In this case I added manually 3 "INNER JOIN" and I would like to dynamically adapt query with history of name. Imagine if toto5, toto6 exists. This is where I am stuck and I don't know how to solve my problem.
I have 3 tables ,StudentInfos,LectureInfos, LectureStudentInfos . I have added some info into them. LectureStudentInfos includes 2 Foreign Keys from other 2 tables. Simply i created many-to-many relation between them. Now i need to add a row into LectureStudentInfos to be able to enter info about which student are selected which subject. Or which lectured selected by which students. But in this way im having an error.. What am i mıssing here?
CREATE DATABASE semesterDB;
CREATE TABLE StudentInfos(StudentId INT NOT NULL AUTO_INCREMENT, studentName VARCHAR(100) NOT NULL, PRIMARY KEY ( StudentId ));
INSERT INTO StudentInfos (studentName) VALUES ("Didi"), ("Steve"), ("Jasmin"), ("Laura"), ("Nancy"), ("Jordan"), ("Matt"), ("Katie"), ("Rose"), ("Lily");
CREATE TABLE LectureInfos(LecturetId INT NOT NULL AUTO_INCREMENT, lectureName VARCHAR(100) NOT NULL, lectureCredits CHAR(10) NOT NULL, PRIMARY KEY ( LecturetId ));
INSERT INTO LectureInfos (lectureName, lectureCredits) VALUES ("Quality management and quality management tools", "6"), ("Business Intelligence", "3"), ("Investment / financing and operational controlling", "3"), ("Application field health or trade or automotive industry", "6"), ("Creative negotiation and English", "6"), ("Corporate project, project and process controlling", "6");
CREATE TABLE LectureStudentInfos (
StudentId int NOT NULL,
LecturetId int NOT NULL,
FOREIGN KEY (StudentId) REFERENCES StudentInfos(StudentId), FOREIGN KEY (LecturetId) REFERENCES LectureInfos(LecturetId));
INSERT INTO LectureStudentInfos (StudentId, LecturetId) VALUES (1, 1), (1,2), (1,3), (2, 1), (2,2), (3,3),(3, 1), (3,2), (4,3),(4, 1), (4,2), (4,4), (4, 5), (4,6), (5,1),(5, 5), (6,2), (6,3),(6,5), (7,3), (7, 1), (7,2), (8,3),(8, 1), (8,2), (9,3),(9, 1), (9,2), (9,4), (9, 5), (10,6), (10,1);
Thanks to #PaulSpiegel
CREATE TABLE StudentInfos(StudentId INT NOT NULL AUTO_INCREMENT, studentName VARCHAR(100) NOT NULL, PRIMARY KEY ( StudentId ));
INSERT INTO StudentInfos (studentName) VALUES ("Didi"), ("Steve"), ("Jasmin"), ("Laura"), ("Nancy"), ("Jordan"), ("Matt"), ("Katie"), ("Rose"), ("Lily");
CREATE TABLE LectureInfos(LecturetId INT NOT NULL AUTO_INCREMENT, lectureName VARCHAR(100) NOT NULL, lectureCredits CHAR(10) NOT NULL, PRIMARY KEY ( LecturetId ));
INSERT INTO LectureInfos (lectureName, lectureCredits) VALUES ("Quality management and quality management tools", "6"), ("Business Intelligence", "3"), ("Investment / financing and operational controlling", "3"), ("Application field health or trade or automotive industry", "6"), ("Creative negotiation and English", "6"), ("Corporate project, project and process controlling", "6");
CREATE TABLE LectureStudentInfos (
StudentId int NOT NULL,
LecturetId int NOT NULL,
PRIMARY KEY (StudentId, LecturetId),
FOREIGN KEY (StudentId) REFERENCES StudentInfos(StudentId),
FOREIGN KEY (LecturetId) REFERENCES LectureInfos(LecturetId)
);
INSERT INTO LectureStudentInfos (StudentId, LecturetId) VALUES (1, 1), (1,2), (1,3), (2, 1), (2,2), (3,3),(3, 1), (3,2), (4,3),(4, 1), (4,2), (4,4), (4, 5), (4,6), (5,1),(5, 5), (6,2), (6,3),(6,5), (7,3), (7, 1), (7,2), (8,3),(8, 1), (8,2), (9,3),(9, 1), (9,2), (9,4), (9, 5), (10,6), (10,1):
I was preparing to create a website using PHPMyAdmin and I bang into a problem : I don't understant why my code does things I don't want.
This is the code to create the tables and some random entries :
create table stud (
matrnr int primary key,
pname Varchar(30) not null
);
create table prof (
persnr int primary key,
pname Varchar(50) not null
);
create table vorl (
vorlnr int primary key,
titel varchar(50),
prof int references prof(persnr) on delete set null
);
create table prüfen (
stud int references stud(matrnr) on delete cascade,
vorl int references vorl(vorlnr),
prof int references prof(persnr) on delete set null,
note float,
primary key(Stud, vorl)
);
insert into stud values
(1, 'G'),
(2, 'F'),
(3, 'C');
insert into Prof values
(1, 'M'),
(2, 'L'),
(3, 'M');
insert into vorl values
(1, 'Info1', 'M'),
(1, 'Info2', 'L'),
(1, 'Info3', 'M');
insert into prüfen values
(1, 1, 1, 2.0),
(1, 2, 1, 1.7),
(2, 3, 2, 2.3);
At this position I tried
Insert into prüfen values (3, 1, 4, 2.0);
but the was still only 3 lines in the table prüfen.
Any help is wellcome.
Have a good week.
Your final insert failed because it references a professor with a prof ID of 4, which does not exist in the prof table.
If you look closely at your definition for the prüfen table, this will be more clear:
create table prüfen (
stud int references stud(matrnr) on delete cascade,
vorl int references vorl(vorlnr),
prof int references prof(persnr) on delete set null,
note float,
primary key(Stud, vorl)
);
The field prof is a foreign key into the prof table. MySQL will require that this field references a professor which actually exists. It does not in the case of your final insert. To get around this error, you could create such a professor, e.g.
insert into Prof values
(4, 'M');
You didn't report an error in your question, which seems off to me. Maybe you failed to mention it, or perhaps your error reporting is turned off for some reason.
Im trying to add in this data. However, It's not allowing me. How do I add the grades in that is also linked to the student?
The error code that is appear is "
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (university.grade_report, CONSTRAINT grade_report_ibfk_1 FOREIGN KEY (Student_number) REFERENCES STUDENT (Student_number))
Possible Solution?
Create database UNIVERSITY;
USE UNIVERSITY;
CREATE TABLE STUDENT(
Name VARCHAR(150),
Student_number INT,
Class INT,
Major VARCHAR(50),
PRIMARY KEY (Student_number)
);
CREATE TABLE UNIT (
Unit_name VARCHAR(120),
Unit_number VARCHAR(20),
Credit INT,
School VARCHAR(10),
PRIMARY KEY (Unit_number)
);
CREATE TABLE SECTION (
Section_id INT,
Unit_number VARCHAR(20),
Semester INT,
Year INT,
Lecturer VARCHAR(150),
PRIMARY KEY (Section_id),
FOREIGN KEY (Unit_number) REFERENCES UNIT(Unit_number)
);
CREATE TABLE GRADE_REPORT (
Student_number INT,
Section_id INT,
Grade INT,
FOREIGN KEY (Student_number) REFERENCES STUDENT(Student_number),
FOREIGN KEY (Section_id) REFERENCES SECTION (Section_id)
);
INSERT INTO STUDENT
VALUES
('Smith', 17, 1, 'CS'),
('Brown', 8, 2, 'CS’);
INSERT INTO UNIT
VALUES
(‘Intro to CS’, ‘IN101’, 8, ‘CS’),
(‘Data Structures’, ‘CS302’, 8, ‘CS’),
(‘Database’, ‘IAB130’, 8, ‘IS’),
(‘Discrete Maths’, ‘MATH120’, 10, ‘MATH’);
INSERT INTO SECTION
VALUES
(85, ‘IN101’, 1, 2012, ‘Smith’),
(102, ‘CS302’, 1, 2012, ‘King’),
(103, ‘IN101’, 2, 2013, ‘Baily’),
(96, ‘MATH120’, 1, 2012, ‘Jones’);
Problem is here:
INSERT INTO GRADE_REPORT
VALUES
(17, 85, 7),
(8, 103, 5),
(8, 102, 6),
(8, 85, 6),
(9, 85, 5),
(17, 96, 4);
U must defined the field for each data destination like this
INSERT INTO GRADE_REPORT (`Student_number`,`Section_id`,`Grade`) VALUES (17, 85, 7), (8, 103, 5), (8, 102, 6), (8, 85, 6), (9, 85, 5), (17, 96, 4);
I need to improve a query similar to the following which simply performs a count based on some filtering while also joining a second table. The books table could have million of records.
CREATE TABLE author
(id int auto_increment primary key, name varchar(20), style varchar(20));
CREATE TABLE books
(
id int auto_increment primary key not null,
author_id int not null,
title varchar(20) not null,
level int not null,
date datetime not null,
CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES author(id)
);
CREATE INDEX idx_level_date ON books(level, date);
INSERT INTO author
(name, style)
VALUES
('John', 'Fact'),
('Sarah', 'Fact'),
('Michael', 'Fiction');
INSERT INTO books
(id, author_id, title, level, date)
VALUES
(1, 1, 'John Book 1', 1, '2012-01-13 13:10:30'),
(2, 1, 'John Book 2', 1, '2011-03-12 12:10:20'),
(3, 1, 'John Book 3', 2, '2012-01-23 12:40:30'),
(4, 2, 'Sarah Book 1', 1, '2009-10-15 13:10:30'),
(5, 2, 'Sarah Book 2', 2, '2013-01-30 12:10:30'),
(6, 3, 'Michael Book 1', 3, '2012-11-13 12:10:30');
It runs extremely quickly once I remove the join but I really need the join in there as I may need to filter based on the author table.
Can anyone help by suggesting potentially more indexing that could help speed things up.
You always need to index foreign key fields as well as primary key fields.