Related
I'm trying to doing this exercise
Extract from the database all the records relating to the "Mathematics" lessons ('docenti.materia' column) of the teacher ('docenti' table) Andrea Bianchi with the participant ('partecipanti' table) Mario Rossi
db sql file
-- phpMyAdmin SQL Dump
-- version 5.2.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Dec 17, 2022 at 04:13 PM
-- Server version: 8.0.30
-- PHP Version: 8.1.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `school`
--
-- --------------------------------------------------------
--
-- Table structure for table `docenti`
--
CREATE TABLE `docenti` (
`id` bigint UNSIGNED NOT NULL,
`id_persona_fisica` bigint UNSIGNED NOT NULL,
`materia` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `docenti`
--
INSERT INTO `docenti` (`id`, `id_persona_fisica`, `materia`) VALUES
(9, 2, 'Matematica'),
(10, 6, 'Storia'),
(11, 3, 'Filosofia');
-- --------------------------------------------------------
--
-- Table structure for table `lezioni`
--
CREATE TABLE `lezioni` (
`id` bigint UNSIGNED NOT NULL,
`id_docente` bigint UNSIGNED NOT NULL,
`giorno` date NOT NULL,
`ora_inizio` time NOT NULL DEFAULT '15:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `lezioni`
--
INSERT INTO `lezioni` (`id`, `id_docente`, `giorno`, `ora_inizio`) VALUES
(47, 11, '2022-04-26', '15:00:00'),
(48, 11, '2022-04-19', '15:00:00'),
(49, 11, '2022-12-27', '15:00:00'),
(50, 11, '2022-12-20', '15:00:00'),
(51, 9, '2022-03-30', '15:00:00'),
(52, 9, '2022-04-27', '15:00:00'),
(53, 9, '2022-04-20', '15:00:00'),
(54, 9, '2022-04-13', '15:00:00'),
(55, 9, '2022-12-23', '15:00:00'),
(56, 9, '2022-12-30', '15:00:00'),
(57, 9, '2022-11-25', '15:00:00'),
(58, 9, '2022-11-18', '15:00:00'),
(59, 9, '2022-12-09', '15:00:00'),
(60, 9, '2022-12-04', '15:00:00'),
(61, 10, '2022-12-26', '15:00:00'),
(62, 10, '2022-12-19', '15:00:00'),
(63, 10, '2022-12-12', '15:00:00'),
(64, 10, '2022-11-28', '15:00:00'),
(65, 10, '2022-11-21', '15:00:00'),
(66, 10, '2022-11-14', '15:00:00'),
(67, 10, '2022-04-25', '15:00:00'),
(68, 10, '2022-04-15', '15:00:00'),
(69, 10, '2022-04-11', '15:00:00');
-- --------------------------------------------------------
--
-- Table structure for table `partecipanti`
--
CREATE TABLE `partecipanti` (
`id` bigint UNSIGNED NOT NULL,
`id_persona_fisica` bigint UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `partecipanti`
--
INSERT INTO `partecipanti` (`id`, `id_persona_fisica`) VALUES
(4, 1),
(2, 4),
(5, 5),
(1, 7),
(3, 8);
-- --------------------------------------------------------
--
-- Table structure for table `persona_fisica`
--
CREATE TABLE `persona_fisica` (
`id` bigint UNSIGNED NOT NULL,
`nome` varchar(255) NOT NULL,
`cognome` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `persona_fisica`
--
INSERT INTO `persona_fisica` (`id`, `nome`, `cognome`) VALUES
(1, 'Mario', 'Rossi'),
(2, 'Andrea', 'Bianchi'),
(3, 'Ernesto', 'Pignoccheri'),
(4, 'Rosa', 'Mastro'),
(5, 'Franco', 'Tilder'),
(6, 'Sara', 'Santelli'),
(7, 'Serena', 'Baropoli'),
(8, 'Franco', 'Baglivi');
-- --------------------------------------------------------
--
-- Table structure for table `presenze`
--
CREATE TABLE `presenze` (
`id` bigint UNSIGNED NOT NULL,
`id_lezione` bigint UNSIGNED NOT NULL,
`id_partecipante` bigint UNSIGNED NOT NULL,
`ora_ingresso` time NOT NULL,
`ora_uscita` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `presenze`
--
INSERT INTO `presenze` (`id`, `id_lezione`, `id_partecipante`, `ora_ingresso`, `ora_uscita`) VALUES
(1, 47, 1, '08:00:00', '10:00:00'),
(2, 48, 1, '08:00:00', '10:00:00'),
(3, 49, 1, '08:00:00', '10:00:00'),
(4, 50, 1, '08:00:00', '10:00:00'),
(5, 51, 1, '08:00:00', '10:00:00'),
(6, 52, 1, '08:00:00', '10:00:00'),
(7, 53, 1, '08:00:00', '10:00:00'),
(8, 54, 1, '08:00:00', '10:00:00'),
(9, 55, 1, '08:00:00', '10:00:00'),
(10, 56, 1, '08:00:00', '10:00:00'),
(11, 57, 1, '08:00:00', '10:00:00'),
(12, 58, 1, '08:00:00', '10:00:00'),
(13, 59, 1, '08:00:00', '10:00:00'),
(14, 60, 1, '08:00:00', '10:00:00'),
(15, 61, 1, '08:00:00', '10:00:00'),
(16, 62, 1, '08:00:00', '10:00:00'),
(17, 63, 1, '08:00:00', '10:00:00'),
(18, 64, 1, '08:00:00', '10:00:00'),
(19, 65, 1, '08:00:00', '10:00:00'),
(20, 66, 1, '08:00:00', '10:00:00'),
(21, 67, 1, '08:00:00', '10:00:00'),
(22, 68, 1, '08:00:00', '10:00:00'),
(23, 69, 1, '08:00:00', '10:00:00'),
(24, 68, 2, '08:00:00', '10:00:00'),
(25, 68, 5, '08:00:00', '10:00:00'),
(26, 51, 4, '00:08:00', '00:10:00'),
(27, 52, 4, '00:08:00', '00:10:00'),
(28, 53, 4, '00:08:00', '00:10:00');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `docenti`
--
ALTER TABLE `docenti`
ADD PRIMARY KEY (`id`),
ADD KEY `FK_id_persona_fisica` (`id_persona_fisica`);
--
-- Indexes for table `lezioni`
--
ALTER TABLE `lezioni`
ADD PRIMARY KEY (`id`),
ADD KEY `FK_id_docente` (`id_docente`);
--
-- Indexes for table `partecipanti`
--
ALTER TABLE `partecipanti`
ADD PRIMARY KEY (`id`),
ADD KEY `FK_persona_fisica` (`id_persona_fisica`);
--
-- Indexes for table `persona_fisica`
--
ALTER TABLE `persona_fisica`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `presenze`
--
ALTER TABLE `presenze`
ADD PRIMARY KEY (`id`),
ADD KEY `FK_id_lezione` (`id_lezione`),
ADD KEY `FK_id_partecipante` (`id_partecipante`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `docenti`
--
ALTER TABLE `docenti`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `lezioni`
--
ALTER TABLE `lezioni`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=70;
--
-- AUTO_INCREMENT for table `partecipanti`
--
ALTER TABLE `partecipanti`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `persona_fisica`
--
ALTER TABLE `persona_fisica`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `presenze`
--
ALTER TABLE `presenze`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=29;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `docenti`
--
ALTER TABLE `docenti`
ADD CONSTRAINT `FK_id_persona_fisica` FOREIGN KEY (`id_persona_fisica`) REFERENCES `persona_fisica` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `lezioni`
--
ALTER TABLE `lezioni`
ADD CONSTRAINT `FK_id_docente` FOREIGN KEY (`id_docente`) REFERENCES `docenti` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `partecipanti`
--
ALTER TABLE `partecipanti`
ADD CONSTRAINT `FK_persona_fisica` FOREIGN KEY (`id_persona_fisica`) REFERENCES `persona_fisica` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `presenze`
--
ALTER TABLE `presenze`
ADD CONSTRAINT `FK_id_lezione` FOREIGN KEY (`id_lezione`) REFERENCES `lezioni` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `FK_id_partecipante` FOREIGN KEY (`id_partecipante`) REFERENCES `partecipanti` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
I'm trying with this query but I keep getting a blank line.
SELECT presenze.*, partecipanti.id, partecipanti.id_persona_fisica, persona_fisica.id, persona_fisica.nome, persona_fisica.cognome, docenti.id_persona_fisica, docenti.materia
FROM presenze
JOIN partecipanti ON presenze.id_partecipante = partecipanti.id
JOIN persona_fisica ON partecipanti.id_persona_fisica = persona_fisica.id
JOIN docenti ON docenti.id_persona_fisica = persona_fisica.id
WHERE persona_fisica.nome = 'Mario' AND persona_fisica.cognome = 'Rossi'
AND persona_fisica.nome = 'Andrea' AND persona_fisica.cognome = 'Bianchi'
AND docenti.materia = 'Matematica';
Where am I wrong?
************* S O L V E D *************
In the end I solved it by doing the second JOIN on the 'persona_fisica' table (alias pf2) without putting the 'ON' clause.
Thanks a lot to #blobtub for the tip!
SELECT
presenze.*,
partecipanti.id,
partecipanti.id_persona_fisica,
pf1.id,
pf1.nome,
pf1.cognome,
docenti.id_persona_fisica,
docenti.materia,
pf2.id,
pf2.nome,
pf2.cognome
FROM presenze
JOIN partecipanti
ON presenze.id_partecipante = partecipanti.id
JOIN persona_fisica pf1
ON partecipanti.id_persona_fisica = pf1.id
JOIN persona_fisica pf2
ON docenti.id_persona_fisica = pf2.id
WHERE pf1.nome = 'Mario' AND pf1.cognome = 'Rossi'
AND pf2.nome = 'Andrea' AND pf2.cognome = 'Bianchi'
AND docenti.materia = 'Matematica';
You need to use two joins onto persona_fisica, one for the partecipanti and one for the docenti
See how the persona_fisica table has two relation arrows going from the same attribute (id) on your diagram? This is what tells you you will need two joins if you want to use both relations.
Something like this (I'm afraid my Italian isn't good enough to test it, I'm sorry):
SELECT
lezioni.id_docente,
presenze.*,
partecipanti.id,
partecipanti.id_persona_fisica,
pf1.id,
pf1.nome,
pf1.cognome,
docenti.id_persona_fisica,
docenti.materia,
pf2.id,
pf2.nome,
pf2.cognome
FROM presenze
JOIN partecipanti
ON presenze.id_partecipante = partecipanti.id
JOIN persona_fisica pf1
ON partecipanti.id_persona_fisica = pf1.id
JOIN lezioni
ON presenze.id_lezioni = lezioni.id
JOIN docenti
ON docenti.id = lezioni.id_docenti
JOIN persona_fisica pf2
ON docenti.id_persona_fisica = pf2.id
WHERE pf1.nome = 'Mario' AND pf1.cognome = 'Rossi'
AND pf2.nome = 'Andrea' AND pf2.cognome = 'Bianchi'
AND docenti.materia = 'Matematica';
I have three tables:
jobAreas (id, title)
jobSkills (id,title, jobAreaID)
userSkills (id, userID, jobSkillID)
Each jobSkills entry belongs to a JobArea (linked by foreign key jobAreaID). And each userSkills entry has a JobSkill that is related to a jobSkill.
I am trying to create a SQL select query that will list the number of users that belong to each Job Area.
SELECT ja.id, ja.title, COUNT(*) as numUsers FROM user_skill_types uskills INNER JOIN job_areas ja INNER JOIN skill_types st ON ja.id = st.parent_id GROUP BY ja.id
But the numbers I am getting are not correct.
Given the following example (based on the table structure provided in the question).
CREATE TABLE `jobareas` (
`id` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `jobareas` (`id`, `title`) VALUES
(1, 'area1'),
(2, 'area2'),
(3, 'area3'),
(4, 'area4'),
(5, 'area5'),
(6, 'area6'),
(7, 'area7'),
(8, 'area8');
-- --------------------------------------------------------
CREATE TABLE `jobskills` (
`id` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`jobAreaID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `jobskills` (`id`, `title`, `jobAreaID`) VALUES
(1, 'skill1', 1),
(2, 'skill2', 3),
(3, 'skill3', 3),
(4, 'skill4', 7),
(5, 'skill5', 4),
(6, 'skill6', 5),
(7, 'skill7', 1),
(8, 'skill8', 7),
(9, 'skill9', 6),
(10, 'skill10', 3),
(11, 'skill11', 4),
(12, 'skill12', 2),
(13, 'skill13', 6),
(14, 'skill14', 7),
(15, 'skill15', 2);
-- --------------------------------------------------------
CREATE TABLE `userskills` (
`id` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`jobSkillID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `userskills` (`id`, `userID`, `jobSkillID`) VALUES
(1, 5, 10),
(2, 2, 11),
(3, 4, 14),
(4, 4, 6),
(5, 2, 8),
(6, 6, 9),
(7, 3, 9),
(8, 1, 12),
(9, 1, 3),
(10, 5, 10);
ALTER TABLE `jobareas`
ADD UNIQUE KEY `id` (`id`);
ALTER TABLE `jobskills`
ADD PRIMARY KEY (`id`),
ADD KEY `jobAreaID` (`jobAreaID`);
ALTER TABLE `userskills`
ADD PRIMARY KEY (`id`),
ADD KEY `userID` (`userID`),
ADD KEY `jobSkillID` (`jobSkillID`);
ALTER TABLE `jobskills`
ADD CONSTRAINT `jobskills_ibfk_1` FOREIGN KEY (`jobAreaID`) REFERENCES `jobareas` (`id`);
ALTER TABLE `userskills`
ADD CONSTRAINT `userskills_ibfk_1` FOREIGN KEY (`jobSkillID`) REFERENCES `jobskills` (`id`);
Your query should use DISTINCT.
SELECT COUNT(DISTINCT(`us`.`userID`)) AS `num`,`ja`.`title` FROM `userskills` `us`
INNER JOIN `jobskills` `js` ON `js`.`id` = `us`.`jobSkillID`
INNER JOIN `jobareas` `ja` ON `ja`.`id` = `js`.`jobAreaID`
GROUP BY `ja`.`id`;
The results can be checked in this SQLFiddle
Your SQL Query shared does not seem to match the schema shared. Also you have not specified how to join the job_areas table
Use
select
ja.id, ja.title , count(us.id) as numUsers
from jobAreas ja
INNER JOIN jobSkills js on ja.id = js.jobAreaID
INNER JOIN userSkills us on js.id = us.jobSkillID
GROUP BY ja.id, ja.title
You are probably getting duplicates in your result because of users having multiple skills or jobs having multiple areas, or both. Rather than COUNT(*), use COUNT(DISTINCT userID) to work around that:
SELECT ja.id, ja.title, COUNT(DISTINCT us.userID) as numUsers
FROM jobAreas ja
JOIN jobSkills js ON js.jobAreaID = ja.id
JOIN userSkills us ON us.jobSkillsID = js.id
GROUP BY ja.id, ja.title
Note I've written the query based on the schema in your question. Based on the query you have written, it should probably look something like (it's not clear what the user_skill_types userID column is called, or how to JOIN user_skill_types to job_skills):
SELECT ja.id, ja.title, COUNT(DISTINCT uskills.userID) as numUsers
FROM job_areas ja
JOIN skill_types st ON ja.id = st.parent_id
JOIN user_skill_types uskills ON uskills.jobSkillID = st.id
GROUP BY ja.id, ja.title
I am trying to create a database, but when I run this code, I get this error:
Code 1215: “Cannot add foreign key constraint"
Code:
drop database if exists kat_db;
create database if not exists kat_db;
use kat_db;
create table if not exists Patients
(
PatientID int not null PRIMARY KEY,
PatientName varchar(50),
TypeOfAnimal varchar(50),
DateOfLastApt date,
PatientAge int,
Microchipped boolean,
OwnerID int not null,
DoctorID int not null,
foreign key (OwnerID) references Owners(OwnerID),
foreign key (DoctorID) references Doctors(DoctorID)
);
create table if not exists Owners
(
OwnerID int not null PRIMARY KEY,
OwnerFirstName varchar(50),
OwnerLastName varchar(50),
PatientID int,
OwnerPhone int,
OwnerZip int,
PreferredPaymentMethod varchar(50),
foreign key (PatientID) references Patients(PatientID)
);
create table if not exists Doctors
(
DoctorID int not null PRIMARY KEY,
DoctorFirstName varchar(50),
DoctorLastName varchar(50),
PatientID int,
DoctorPhone int,
DoctorZip int,
AnimalSpecialty varchar(50),
foreign key (PatientID) references Patients(PatientID)
);
insert into Patients (PatientID, TypeOfAnimal, PatientAge, PatientName, DateOfLastApt, Microchipped, DoctorID, OwnerID)
values (01, 'dog', 6, 'Dima', '2017-02-05', 1, 101, 1001),
(02, 'dog', 3, 'Misha', '2017-02-05', 1, 102, 1002),
(03, 'cat', 2, 'Pistol', '2017-06-09', 0, 103, 1003),
(04, 'cat', 1, 'Nessie', '2017-09-04', 0, 104, 1004),
(05, 'cat', 2, 'Charlie', '2016-06-04', 1, 105, 1005),
(06, 'cat', 12, 'Francis', '2015-05-07', 1, 106, 1006),
(07, 'rabbit', 5, 'Bunny', '2015-05-06', 0, 107, 1007),
(08, 'turtle', 6, 'Aqua', '2017-06-08', 0, 108, 1008),
(09, 'dog', 16, 'Sammie', '2012-09-07', 1, 109, 1009),
(10, 'dog', 14, 'Dog', '2016-04-06', 0, 110, 1010);
insert into Owners (OwnerID, OwnerFirstName, OwnerLastName, OwnerPhone, OwnerZip, PreferredPaymentMethod, PatientID)
values (101, 'Kat', 6, 'Dima', '2017-02-05', 1, 101, 1001),
(102, 'Hunter', 3, 'Misha', '2017-02-05', 1, 102, 1002),
(103, 'Vicky', 2, 'Pistol', '2017-06-09', 0, 103, 1003),
(104, 'Vanessa', 1, 'Nessie', '2017-09-04', 0, 104, 1004),
(105, 'Weston', 2, 'Charlie', '2016-06-04', 1, 105, 1005),
(106, 'Jonas', 12, 'Francis', '2015-05-07', 1, 106, 1006),
(107, 'Devin', 5, 'Bunny', '2015-05-06', 0, 107, 1007),
(108, 'Grego', 6, 'Aqua', '2017-06-08', 0, 108, 1008),
(109, 'Jackson', 16, 'Sammie', '2012-09-07', 1, 109, 1009),
(110, 'dog', 14, 'Dog', '2016-04-06', 0, 110, 1010);
insert into Patients (PatientID, TypeOfAnimal, PatientAge, PatientName, DateOfLastApt, Microchipped, DoctorID, OwnerID)
values (01, 'dog', 6, 'Dima', '2017-02-05', 1, 101, 1001),
(02, 'dog', 3, 'Misha', '2017-02-05', 1, 102, 1002),
(03, 'cat', 2, 'Pistol', '2017-06-09', 0, 103, 1003),
(04, 'cat', 1, 'Nessie', '2017-09-04', 0, 104, 1004),
(05, 'cat', 2, 'Charlie', '2016-06-04', 1, 105, 1005),
(06, 'cat', 12, 'Francis', '2015-05-07', 1, 106, 1006),
(07, 'rabbit', 5, 'Bunny', '2015-05-06', 0, 107, 1007),
(08, 'turtle', 6, 'Aqua', '2017-06-08', 0, 108, 1008),
(09, 'dog', 16, 'Sammie', '2012-09-07', 1, 109, 1009),
(10, 'dog', 14, 'Dog', '2016-04-06', 0, 110, 1010);
I tried creating the tables in different order. I also created a different database, which worked, In fact, I used this to create the database on the top.
drop database if exists kat3_db;
create database if not exists kat3_db;
use kat3_db;
create table if not exists Book(
BookNumber int not null,
BookName varchar(50),
BookPrice decimal(5,2),
CoverType varchar(15) default 'hardcover',
PublicationDate date,
primary key (BookNumber)
);
create table if not exists Course(
CourseNo int not null,
CourseName varchar(20),
Semester varchar(10),
BookNumber int not null,
primary key (CourseNo),
foreign key (BookNumber) references Book(BookNumber)
);
insert into Book
(BookNumber, BookName, BookPrice, CoverType, PublicationDate)
values
(1, 'Math', 023.64, 'paperback', '1999-02-05'),
(3, 'English', 999.36, 'e-book', '2013-06-04'),
(5, 'Calc', 056.69, 'paperback', '1964-05-05'),
(6, 'C++', 053.98, 'paperback', '2016-03-04'),
(7, 'Programming', 113.02, 'paperback', '2001-10-11'),
(9, 'Art', 250.99, 'paperback', '1996-11-11'),
(10, 'Networking', 036.64, 'e-book', '2014-05-06'),
(12, 'Drawing', 111.36, 'paperback', '2013-06-04'),
(13, 'Robotics', 012.03, 'e-book', '2016-06-05'),
(14, 'Computer', 25.03, 'e-book', '2001-06-04')
;
insert into Book
(BookNumber, BookName, BookPrice, PublicationDate)
values
(2, 'Reading', 364.20, '2016-06-05'),
(4, 'Database', 036.64, '2017-06-05'),
(8, 'Wellness', 050.00, '1999-10-10'),
(11, 'Linux', 55.36, '2013-06-08'),
(15, 'FYE', 03.01, '1991-02-05')
;
insert into Course
(CourseNo, CourseName, Semester, BookNumber)
values
(111, 'IntroToMath', 'Spring', 1),
(222, 'IntroToReading', 'Fall', 2),
(333, 'IntroToEnglish', 'Spring', 3),
(444, 'IntroToDatabase', 'Fall', 4),
(555, 'IntroToCalc', 'Spring', 5),
(666, 'IntroToC++', 'Spring', 6),
(777, 'IntroToProgramming', 'Fall', 7),
(888, 'IntroToWellness','Spring', 8),
(999, 'IntroToArt', 'Fall', 9),
(010, 'IntroToNetworking', 'Spring', 10),
(011, 'IntroToLinux', 'Fall', 11),
(012, 'IntroToDrawing', 'Spring', 12),
(013, 'IntroToRobotics', 'Fall', 13),
(014, 'IntroToComputer', 'Spring', 14),
(015, 'IntroToFYE', 'Summer', 15)
;
I do not see what I did differently. Any suggestions would be greatly appreciated. If someone can run the first code on top and tell me if it works for them or not, that would be big help also. Thank you!
At the time of creating Patients table, owner and Doctor table information is not available. So it is not allowing you.
So just create the table first.
and then add FK with alter table.
You're adding you tables in the wrong order.
You create the Patients table with foreign key constraints before you create the tables/fields they rely on to exist.
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.
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);