This question already has answers here:
How can I add a foreign key when creating a new table?
(5 answers)
Closed 4 years ago.
I am trying creating two tables, aluno = student and usuario = user. MySQL Workbench keep showing me that codigo in table usario doesn´t exist. Anyone can help me plz?
drop database `web2`;
CREATE DATABASE `web2` DEFAULT CHARSET latin1;
USE `web2`;
CREATE TABLE `aluno` (
`id_aluno` bigint(20) not null auto_increment,
`nome` varchar(100) not null,
`cpf` varchar(20) not null,
`rg` varchar(20) not null,
`dataDeNascimento` date not null,
`endereco` varchar(50),
`cidade` varchar(150),
`telefoneFixo` varchar(14),
`telefoneCelular` varchar(14),
`email` varchar(30) not null,
PRIMARY KEY (`id_aluno`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
INSERT INTO `aluno` (`id_aluno`, `nome`, `cpf`, `rg`,`dataDeNascimento`, `endereco`, `cidade`, `telefoneFixo`,
`telefoneCelular`,`email`) VALUES ('1', 'Marcela', '255665696363', '2153263699',
'1985-07-08', 'Rua Hum', 'Belo Horizonte', '(35)54321-9876', '(35)54321-9876','marcela#bh.mg');
INSERT INTO `aluno` (`id_aluno`, `nome`, `cpf`, `rg`,`dataDeNascimento`, `endereco`, `cidade`, `telefoneFixo`,
`telefoneCelular`,`email`) VALUES ('2', 'Paulo', '275865696361', '2183255599','1983-02-05', 'Rua Dois', 'Bela Vista', '(11)12345-6789',
'(11)12345-6789', 'paulo#saopaulo.sp');
INSERT INTO `aluno` (`id_aluno`, `nome`, `cpf`, `rg`,`dataDeNascimento`, `endereco`, `cidade`, `telefoneFixo`,
`telefoneCelular`,`email`) VALUES ('3', 'Marcos', '275812656361', '2183255599','1983-02-12', 'Rua Dois', 'Bela Vista', '(11)12345-6790',
'(11)12345-6789', 'paulo#saopaulo.sp');
INSERT INTO `aluno` (`id_aluno`, `nome`, `cpf`, `rg`,`dataDeNascimento`, `endereco`, `cidade`, `telefoneFixo`,
`telefoneCelular`,`email`) VALUES ('4', 'Rodolfo', '569865696361', '2183255599','1983-05-28', 'Rua Dois', 'Bela Vista', '(11)12345-6791',
'(11)12345-6789', 'paulo#saopaulo.sp');
INSERT INTO `aluno` (`id_aluno`, `nome`, `cpf`, `rg`,`dataDeNascimento`, `endereco`, `cidade`, `telefoneFixo`,
`telefoneCelular`,`email`) VALUES ('5', 'Larissa', '275865696361', '2183255599','1983-02-01', 'Rua Dois', 'Bela Vista', '(11)12345-6792',
'(11)12345-6789', 'paulo#saopaulo.sp');
CREATE TABLE `usuario` (
`id` bigint(20) not null auto_increment,
`login` varchar(10) not null,
`senha` varchar(10) not null,
PRIMARY KEY (`id`),
FOREIGN KEY (`codigo`) REFERENCES aluno (`id_aluno`),
UNIQUE KEY (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
INSERT INTO `usuario` (`id`, `login`, `senha`, `codigo` ) VALUES ('1', 'marcela', '54321', '1');
INSERT INTO `usuario` (`id`, `login`, `senha`, `codigo` ) VALUES ('2', 'paulo', '12345', '2');
INSERT INTO `usuario` (`id`, `login`, `senha`, `codigo` ) VALUES ('3', 'gustavo', '52321', '3');
INSERT INTO `usuario` (`id`, `login`, `senha`, `codigo` ) VALUES ('4', 'leandro', '19315', '4');
INSERT INTO `usuario` (`id`, `login`, `senha`, `codigo` ) VALUES ('5', 'bruna', '14045', '5');
Are you missing the "codigo" column name in "CREATE TABLE usuario"
...
`codigo` bigint(20)
...
You need codigo defined in create table statement:
CREATE TABLE `usuario` (
`id` bigint(20) not null auto_increment,
`login` varchar(10) not null,
`senha` varchar(10) not null,
`codigo` bigint(20)
PRIMARY KEY (`id`),
FOREIGN KEY (`codigo`) REFERENCES aluno (`id_aluno`),
UNIQUE KEY (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
The reason for this is that foreign keys are constraints applied to columns, so the table first needs the column to which the foreign key constraint is applied.
Related
I have been trying to find out what or where this "unknown column" error is coming from. To my untrained eyes, the code looks ok from a syntax point of view. Obviously I'm missing something though..I get an error 1054.
Here is the database (it's only a little one). Can someone please tell what is going on?
The error refers to the INSERT INTO statement for the enrolment table.
-- MySQL Workbench Forward Engineering
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema BR000726910
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `BR000726910` ;
-- -----------------------------------------------------
-- Schema BR000726910
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `BR000726910` DEFAULT CHARACTER SET utf8 ;
USE `BR000726910` ;
-- -----------------------------------------------------
-- Table `BR000726910`.`school`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `BR000726910`,`school` ;
CREATE TABLE IF NOT EXISTS `BR000726910`.`school` (
`SchoolName` VARCHAR(30) NOT NULL,
`Address` VARCHAR(30) NULL,
`PhoneNumber` VARCHAR(10) NULL,
`Email` VARCHAR(30) NULL,
PRIMARY KEY (`SchoolName`))
ENGINE = InnoDB;
INSERT INTO `school` (`SchoolName`, `Address`, `PhoneNumber`, `Email` )
VALUES ('Heartbreak_High', '46_Ratloch_Road_Craiglang', '0882346000', 'PimpZ#Hotrods.com' );
-- -----------------------------------------------------
-- Table `BR000726910`.`student`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `BR000726910`,`student` ;
CREATE TABLE IF NOT EXISTS `BR000726910`.`student` (
`StudentID` INT(8) NOT NULL,
`FirstName` VARCHAR(20) NULL,
`MiddleInitial` VARCHAR(5) NULL,
`LastName` VARCHAR(20) NULL,
`PhoneNumber` VARCHAR(10) NULL,
`ResidentialAddress` VARCHAR(30) NULL,
`Email` VARCHAR(50) NULL,
`DateOfBirth` DATE NULL,
`DateOfEnrolment` DATE NULL,
`Gender` CHAR(1) NULL,
`school_SchoolName` VARCHAR(30) NULL,
PRIMARY KEY (`StudentID`),
INDEX `fk_student_school1_idx` (`school_SchoolName` ASC) VISIBLE,
CONSTRAINT `fk_student_school1`
FOREIGN KEY (`school_SchoolName`)
REFERENCES `BR000726910`.`school` (`SchoolName`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
INSERT INTO `student` (`StudentID`, `FirstName`, `MiddleInitial`, `LastName`, `PhoneNumber`, `ResidentialAddress`, `Email`, `DateOfBirth`, `DateOfEnrolment`,
`Gender`) VALUES ('10002340', 'Benjamin', 'J', 'Roberts', '0476066591', 'Bermuda_Triangle', 'Goober#Ringworm.com', '1937-06-21', '1788-01-26', 'M' );
INSERT INTO `student` (`StudentID`, `FirstName`, `MiddleInitial`, `LastName`, `PhoneNumber`, `ResidentialAddress`, `Email`, `DateOfBirth`, `DateOfEnrolment`,
`Gender`) VALUES ('18831492', 'John', 'F', 'Kennedy', '0418812345', 'Arlington_National_Cemetary', 'conspiracy#theory.com', '1931-06-04', '2021-02-21', 'M' );
INSERT INTO `student` (`StudentID`, `FirstName`, `MiddleInitial`, `LastName`, `PhoneNumber`, `ResidentialAddress`, `Email`, `DateOfBirth`, `DateOfEnrolment`,
`Gender`) VALUES ('10110001', 'Homer', 'J', 'Simpson', '0400000001', '12_Donut_Street,Springfield', 'mmmdonuts#greedyguts.com', '1901-01-01', '2021-03-21', 'M' );
INSERT INTO `student` (`StudentID`, `FirstName`, `MiddleInitial`, `LastName`, `PhoneNumber`, `ResidentialAddress`, `Email`, `DateOfBirth`, `DateOfEnrolment`,
`Gender`) VALUES ('14921883', 'Jesus', 'H', 'Christ', '043142000', '01_Big_Bang_Avenue_Universe', 'praytoday#foryoursoul.com', '0001-12-25', '1238-09-20', 'M' );
INSERT INTO `student` (`StudentID`, `FirstName`, `MiddleInitial`, `LastName`, `PhoneNumber`, `ResidentialAddress`, `Email`, `DateOfBirth`, `DateOfEnrolment`,
`Gender`) VALUES ('19876543', 'Hannibal', 'K', 'Lecter', '0433666999', '02_Dank_Cell_CrazyTown', 'favabeans#chianti.com', '1949-03-27', '1111-12-13', 'M' );
-- -----------------------------------------------------
-- Table `BR000726910`.`teacher`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `BR000726910`,`teacher` ;
CREATE TABLE IF NOT EXISTS `BR000726910`.`teacher` (
`TeacherID` INT(8) NOT NULL,
`FirstName` VARCHAR(20) NULL,
`MiddleInitial` VARCHAR(5) NULL,
`Surname` VARCHAR(20) NULL,
`Email` VARCHAR(50) NULL,
`PhoneNumber` VARCHAR(10) NULL,
`school_SchoolName` VARCHAR(30) NULL,
PRIMARY KEY (`TeacherID`),
INDEX `fk_teacher_school1_idx` (`school_SchoolName` ASC) VISIBLE,
CONSTRAINT `fk_teacher_school1`
FOREIGN KEY (`school_SchoolName`)
REFERENCES `BR000726910`.`school` (`SchoolName`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
INSERT INTO `teacher` (`TeacherID`, `FirstName`, `MiddleInitial`, `Surname`, `Email`, `PhoneNumber`)
VALUES ('42424242', 'Vlad', 'D', 'Impaler', 'Beachbunny#wrongendofthestick.com', '082814444' );
INSERT INTO `teacher` (`TeacherID`, `FirstName`, `MiddleInitial`, `Surname`, `Email`, `PhoneNumber`)
VALUES ('48241206', 'Pablo', 'S', 'Cabar', 'DrugNazi#sinoloacartel.com', '1800008110' );
INSERT INTO `teacher` (`TeacherID`, `FirstName`, `MiddleInitial`, `Surname`, `Email`, `PhoneNumber`)
VALUES ('40801603', 'Tee', 'N', 'Wolf', 'dogbreath#hairloss.com', '0403020100' );
INSERT INTO `teacher` (`TeacherID`, `FirstName`, `MiddleInitial`, `Surname`, `Email`, `PhoneNumber`)
VALUES ('45677654', 'Wile', 'E', 'Coyote', 'winnerwinner#chickendinner.com', '0413579111' );
-- -----------------------------------------------------
-- Table `BR000726910`.`subject`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `BR000726910`,`subject` ;
CREATE TABLE IF NOT EXISTS `BR000726910`.`subject` (
`SubjectCode` VARCHAR(9) NOT NULL,
`TeacherID` INT(8) NOT NULL,
`SubjectDescription` VARCHAR(300) NULL,
`CostofSubject` DECIMAL(6,2) NOT NULL,
`CourseDuration` INT(3) NULL,
`NumberAssessmentItems` INT(3) NULL,
PRIMARY KEY (`SubjectCode`),
INDEX `fk_subject_teacher1_idx` (`TeacherID` ASC) VISIBLE,
CONSTRAINT `fk_subject_teacher1`
FOREIGN KEY (`TeacherID`)
REFERENCES `BR000726910`.`teacher` (`TeacherID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
INSERT INTO `subject` (`SubjectCode`, `TeacherID`, `SubjectDescription`, `CostofSubject`, `CourseDuration`, `NumberAssessmentItems` )
VALUES ('WEBSQL001', '42424242', 'A searing treatise on the seismic shifts taking place in the world of database stuff', '1200.00', '12', '3' );
INSERT INTO `subject` (`SubjectCode`, `TeacherID`, `SubjectDescription`, `CostofSubject`, `CourseDuration`, `NumberAssessmentItems` )
VALUES ('PYTHON101', '48241206', 'A charming voyage of self discovery looking at a snake coming of age', '1955.06', '12', '2' );
INSERT INTO `subject` (`SubjectCode`, `TeacherID`, `SubjectDescription`, `CostofSubject`, `CourseDuration`, `NumberAssessmentItems` )
VALUES ('BVHL90210', '40801603', 'The comatose idiocy of millenials trying to adult', '1000.00', '12', '56' );
INSERT INTO `subject` (`SubjectCode`, `TeacherID`, `SubjectDescription`, `CostofSubject`, `CourseDuration`, `NumberAssessmentItems` )
VALUES ('STRP00001', '45677654', 'Learn the exciting art of Latvian pole dancing', '49.94', '12', '1' );
-- -----------------------------------------------
-- Table `BR000726910`.`enrolment`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `BR000726910`,`enrolment` ;
CREATE TABLE IF NOT EXISTS `BR000726910`.`enrolment` (
`Grade` VARCHAR(4) NOT NULL,
`ResultForStudent` INT(3) NOT NULL,
`DateOfGrade` DATE NULL,
`student_StudentID` INT(8) NOT NULL,
`subject_SubjectCode` VARCHAR(9) NOT NULL,
PRIMARY KEY (`Grade`),
INDEX `fk_enrolment_student1_idx` (`student_StudentID` ASC) VISIBLE,
INDEX `fk_enrolment_subject1_idx` (`subject_SubjectCode` ASC) VISIBLE,
CONSTRAINT `fk_enrolment_student1`
FOREIGN KEY (`student_StudentID`)
REFERENCES `BR000726910`.`student` (`StudentID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_enrolment_subject1`
FOREIGN KEY (`subject_SubjectCode`)
REFERENCES `BR000726910`.`subject` (`SubjectCode`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade`, `StudentID`, `SubjectCode`)
VALUES ('CRED', '78', '1981-03-03', '10002340', 'BVHL90210');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade`, `StudentID`, `SubjectCode`)
VALUES ('FAIL', '32', '1981-09-15' , '10110001', 'PYTHON101');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade`, `StudentID`, `SubjectCode`)
VALUES ('PASS', '61', '1981-11-08' , '14921883', 'WEBSQL001');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('CRED', '71', '1981-09-15' , '18831492', 'STRP00001');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade`, `StudentID`, `SubjectCode` )
VALUES ('CRED', '74', '1981-09-15' , '19876543', 'BVHL90210');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('DIST' , '98', '1981-09-15', '10002340', 'PYTHON101');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('DIST', '91', '1981-09-15' , '10110001', 'WEBSQL001');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('CRED', '75', '1988-08-15', '14921883', 'STRP00001');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('PASS', '63', '1981-09-15', '18831492', 'BVHL90210');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('FAIL', '12', '1981-09-14', '19876543', 'PYTHON101');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('CRED', '80', '1981-09-15', '10002340', 'WEBSQL001');
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade`, `StudentID`, `SubjectCode` )
VALUES ('CRED', '80', '1981-09-15', '10110001', 'STRP00001' );
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('DIST', '98', '1981-09-15', '14921883', 'BVHL90210' );
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('DIST', '98', '1981-09-15', '18831492', 'PYTHON101' );
INSERT INTO `enrolment` (`Grade`, `ResultForStudent`, `DateOfGrade` , `StudentID`, `SubjectCode`)
VALUES ('DIST', '98', '1981-09-15', '19876543', 'WEBSQL001' );
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
Not sure what i'm doing wrong here. Im trying to understand the relationships between tables? Please help thank you
DROP DATABASE IF EXISTS `sql_retail`;
CREATE DATABASE `sql_retail`;
USE `sql_retail`;
SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;
CREATE TABLE `RETAIL_ORDER` (
`OrderNumber` int(4) NOT NULL,
`StoreNumber` int(2) NOT NULL,
`StoreZip` char(9) NOT NULL,
`OrderMonth` char(12) NOT NULL,
`OrderYear` int(4) NOT NULL,
`OrderTotal` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `RETAIL_ORDER` VALUES (1000, 10, 98110, 'December', 2017, 445.00);
INSERT INTO `RETAIL_ORDER` VALUES (2000, 20, 02335, 'December', 2017, 310.00);
INSERT INTO `RETAIL_ORDER` VALUES (3000, 10, 98110, 'January', 2018, 480.00);
CREATE TABLE `ORDER_ITEM` (
`OrderNumber` int(11) NOT NULL,
`SKU` int(7) NOT NULL,
`Quantity` int(6) NOT NULL,
`Price` float(10) NOT NULL,
`Extended Price` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`),FOREIGN KEY(`OrderNumber`)REFERENCES RETAIL_ORDER(`OrderNumber`),
FOREIGN KEY(`SKU`)REFERENCES SKU_DATA(`SKU`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `ORDER_ITEM` VALUES (1000, 201000, 1, 300.00, 300.00);
INSERT INTO `ORDER_ITEM` VALUES (1000, 202000, 1, 130.00, 130.00);
INSERT INTO `ORDER_ITEM` VALUES (2000, 101100, 4, 50.00, 200.00);
INSERT INTO `ORDER_ITEM` VALUES (2000, 101200, 2, 50.00, 100.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 100200, 1, 300.00, 300.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 101100, 2, 50.00, 100.00);
INSERT INTO `ORDER_ITEM` VALUES (3000, 101200, 1, 50.00, 50.00);
CREATE TABLE `SKU_DATA` (
`SKU` int(11) NOT NULL,
`SKU_Description` varchar(50) NOT NULL,
`Department` varchar(20) NOT NULL,
`Buyer` varchar(15) NOT NULL,
PRIMARY KEY (`SKU`),FOREIGN KEY(`Buyer`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `SKU_DATA` VALUES (100100, 'Std. Scuba Tank, Yellow', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100200, 'Std. Scuba Tank, Magenta', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100300, 'Std. Scuba Tank, Light Blue', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100400, 'Std. Scuba Tank, Dark Blue', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100500, 'Std. Scuba Tank, Light Green', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (100600, 'Std. Scuba Tank, Dark Green', 'Water Sports', 'Peter Hansen');
INSERT INTO `SKU_DATA` VALUES (101100, 'Dive Mask, Small Clear', 'Water Sports', 'Nancy Meyers');
INSERT INTO `SKU_DATA` VALUES (101200, 'Dive Mask, Med Clear', 'Water Sports', 'Nancy Meyers');
INSERT INTO `SKU_DATA` VALUES (201000, 'Half dome tent', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (202000, 'Half dome tent vestibule', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (203000, 'Half dome tent vestibule wide', 'camping', 'Cindy Lo');
INSERT INTO `SKU_DATA` VALUES (301000, 'Light fly climbing harness', 'climbing', 'Jerry Martin');
INSERT INTO `SKU_DATA` VALUES (302000, 'Locking Carabiner, Oval', 'climbing', 'Jerry Martin');
CREATE TABLE `BUYER` (
`BuyerName` varchar(15) NOT NULL,
`Department` varchar(15) NOT NULL,
`Position` varchar(15) NOT NULL,
`Supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`BuyerName`),FOREIGN KEY(`Supervisor`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `SKU_DATA` VALUES ('Cindy Lo', 'Purchasing', 'Buyer 2', 'Mary Smith');
INSERT INTO `SKU_DATA` VALUES ('Jerry Martin', 'Purchasing', 'Buyer 1', 'Cindo Lo');
INSERT INTO `SKU_DATA` VALUES ('Mary Smith', 'Purchasing', 'Manager','' );
INSERT INTO `SKU_DATA` VALUES ('Nancy Meyers', 'Purchasing', 'Buyer 1', 'Pete Hansen');
INSERT INTO `SKU_DATA` VALUES ('Pete Hansen', 'Purchasing', 'Buyer 3', 'Mary Smith');
You have some errors.
First you assign a foreign key to a table that don't exists yet and second you have duplicate values into your inserts for your primary keys.
I have fixed your table creation, check your insert datas.
Follow below approach to create your tables and then do the inserts:
DROP DATABASE IF EXISTS sql_retail ;
CREATE DATABASE sql_retail ;
USE sql_retail ;
SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;
CREATE TABLE `RETAIL_ORDER` (
`OrderNumber` int(4) NOT NULL,
`StoreNumber` int(2) NOT NULL,
`StoreZip` char(9) NOT NULL,
`OrderMonth` char(12) NOT NULL,
`OrderYear` int(4) NOT NULL,
`OrderTotal` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `ORDER_ITEM` (
`OrderNumber` int(11) NOT NULL,
`SKU` int(7) NOT NULL,
`Quantity` int(6) NOT NULL,
`Price` float(10) NOT NULL,
`Extended Price` float(10) NOT NULL,
PRIMARY KEY (`OrderNumber`),
FOREIGN KEY(`OrderNumber`)REFERENCES RETAIL_ORDER(`OrderNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `SKU_DATA` (
`SKU` int(11) NOT NULL,
`SKU_Description` varchar(50) NOT NULL,
`Department` varchar(20) NOT NULL,
`Buyer` varchar(15) NOT NULL,
PRIMARY KEY (`SKU`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE ORDER_ITEM ADD FOREIGN KEY(`SKU`)REFERENCES SKU_DATA(`SKU`);
CREATE TABLE `BUYER` (
`BuyerName` varchar(15) NOT NULL,
`Department` varchar(15) NOT NULL,
`Position` varchar(15) NOT NULL,
`Supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`BuyerName`),
FOREIGN KEY(`Supervisor`)REFERENCES BUYER(`BuyerName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
ALTER TABLE SKU_DATA ADD FOREIGN KEY(`Buyer`)REFERENCES BUYER(`BuyerName`);
Demo: https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/28
This question already has answers here:
MySQL Error 1215: Cannot add foreign key constraint
(29 answers)
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 2 years ago.
I want to add foreign key like this
and this is my table user_idea
CREATE TABLE IF NOT EXISTS `user_idea` (
`idea_id` int(5) NOT NULL AUTO_INCREMENT,
`user_id` varchar(30) DEFAULT NULL,
`title` varchar(40) DEFAULT NULL,
`innovators` varchar(30) DEFAULT NULL,
`idea_categories` varchar(30) DEFAULT NULL,
`status` int(5) DEFAULT NULL,
`description` varchar(50) DEFAULT NULL,
PRIMARY KEY (`idea_id`),
KEY `innovators` (`innovators`),
KEY `idea_categories` (`idea_categories`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data untuk tabel `user_idea`
--
INSERT INTO `user_idea` (`idea_id`, `user_id`, `title`, `innovators`, `idea_categories`, `status`, `description`) VALUES
(1, 'jack', 'Video Annotations', 'jack', '1;2', 1, 'Video Annotations Description'),
(2, 'jack', 'Optimize waterfall model', 'jack;jackson', '3', 0, 'Optimize waterfall model Description'),
(3, 'jackson', 'Automation', 'jackson', '1', 1, 'Automation Description'),
(4, 'jackson', 'Design Patterns', 'jackson', '1', 0, 'Design Patterns Description'),
(5, 'alice', 'Identify Video Objects', 'alice;jack', '2', 1, 'Identify Video Objects Description'),
(6, 'bob', 'Tin Can LMS', 'bob', '1', 1, 'Tin Can LMS Description'),
(7, 'bob', 'Text Summarization', 'bob', '2;3', 0, 'Text Summarization Description');
--
-- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables)
--
--
-- Ketidakleluasaan untuk tabel `user_idea`
--
ALTER TABLE `user_idea`
ADD CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user_info` (`id`);
my table idea_category
enter image description here
CREATE TABLE IF NOT EXISTS `idea_categories` (
`category_id` int(5) NOT NULL AUTO_INCREMENT,
`category_name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `idea_categories` (`category_id`, `category_name`) VALUES
(1, 'Project Lifecycle'),
(2, 'Video'),
(3, 'Language Analysis');
My table user_info:
enter image description here
CREATE TABLE IF NOT EXISTS `user_info` (
`id` varchar(30) NOT NULL,
`full_name` varchar(30) DEFAULT NULL,
`dep_id` int(5) DEFAULT NULL,
`point` int(5) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `dep_id` (`dep_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `user_info` (`id`, `full_name`, `dep_id`, `point`) VALUES
('alice', 'Alice W', 2, 1),
('bob', 'Bob S.', 2, 2),
('jack', 'JACK D.', 2, 2),
('jackson', 'M.S.Jackson', 3, 3);
but I got an error cannot add foreign key? Please help
The object I am referring to is about a entity in the data model.
For example, these are the tables in my database:
-- ----------------------------
-- student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_no` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` tinyint(1) NOT NULL,
`age` tinyint(3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `student` VALUES ('1', '19001', 'John', '1', '13');
INSERT INTO `student` VALUES ('2', '19002', 'Mary', '2', '12');
INSERT INTO `student` VALUES ('3', '19003', 'Tom', '1', '13');
-- ----------------------------
-- course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `course` VALUES ('1', 'C1');
INSERT INTO `course` VALUES ('2', 'C2');
INSERT INTO `course` VALUES ('3', 'C3');
-- ----------------------------
-- score
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_id` int(11) NOT NULL,
`student_id` int(11) NOT NULL,
`score` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `score` VALUES ('1', '1', '1', '100');
INSERT INTO `score` VALUES ('2', '1', '2', '96');
INSERT INTO `score` VALUES ('3', '2', '1', '77');
Student entity includes all data associated with it.
I want to export a student entity named Mary, including all of its associated data (courses, scores)
Through the tool, I want to get the output like the following:
1. json like formats:
{
"id": 2,
"student_no": 19002,
"name": "Mary",
"gender": 2,
"age": 12,
"score": [
{
"id": 2,
"course_id": 1,
"student_id": 2,
"score": 96
}
]
}
2. INSERT statments
INSERT INTO `student` (`id`, `student_no`, `name`, `gender`, `age`) VALUES ('2', '19002', 'Mary', '2', '12');
INSERT INTO `score` (`id`, `course_id`, `student_id`, `score`) VALUES ('2', '1', '2', '96');
Any of the above two formats can help achieve my goal.
purpose
The data associated with Mary is the student record and her course score records, so I hope that this tool can help me transfer data from one database to another, or easily delete any associated records about Mary in a database instead of write the SQL statement myself.
Is there such a tool? The tool should be configurable without writing code, to define the tables involved in the entity and the associated fields between them.
Thank you!
I have a database of the following relations:
Bar(Name, Address, Licence)
Beer(Name,Manufacture)
Drinker(Name,Address)
Frequents(DrinkerName,BarName)
Likes(DrinkerName,BeerName)
Sells(BarName,BeerName,Amount)
Serves(BarName,BeerName)
The Sample DDL Statements:
CREATE TABLE `Bar` (
`Name` varchar(255) NOT NULL,
`Address` varchar(255) DEFAULT NULL,
`Licence` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Bar` (`Name`, `Address`, `Licence`) VALUES
('Deluxe', 'Luxvagen 2', 'Yes'),
('Grace', 'Gracevagen 2', 'Yes'),
('KrogBar', 'Barvagen 2', 'Yes');
CREATE TABLE `Beer` (
`Name` varchar(255) NOT NULL,
`Manufacture` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Beer` (`Name`, `Manufacture`) VALUES
('Carlsberg', 'Coppers'),
('Heiniken', 'Spendrups'),
('Miller', 'DaMill');
CREATE TABLE `Boor` (
`Name` varchar(255) NOT NULL,
`Age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `Drinker` (
`Name` varchar(255) NOT NULL,
`Address` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Drinker` (`Name`, `Address`) VALUES
('Alex', 'Överbar 2'),
('Bam', 'Påbar 2'),
('Emil', 'Mittibar 2'),
('Max', 'Ibar 2'),
('Petra', 'Förebar 2'),
('Rebecca', 'Efterbar 2'),
('Sam', 'Underbar 2');
CREATE TABLE `Frequents` (
`DrinkerName` varchar(255) NOT NULL DEFAULT '',
`BarName` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Frequents` (`DrinkerName`, `BarName`) VALUES
('Emil', 'Deluxe'),
('Max', 'Deluxe'),
('Rebecca', 'Deluxe'),
('Alex', 'Grace'),
('Petra', 'Grace'),
('Bam', 'KrogBar'),
('Sam', 'KrogBar');
CREATE TABLE `Likes` (
`DrinkerName` varchar(255) NOT NULL DEFAULT '',
`BeerName` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Likes` (`DrinkerName`, `BeerName`) VALUES
('Bam', 'Carlsberg'),
('Emil', 'Carlsberg'),
('Rebecca', 'Carlsberg'),
('Emil', 'Heiniken'),
('Max', 'Heiniken'),
('Petra', 'Heiniken'),
('Sam', 'Heiniken'),
('Alex', 'Miller');
CREATE TABLE `Sells` (
`BarName` varchar(100) DEFAULT NULL,
`BeerName` varchar(100) DEFAULT NULL,
`Amount` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Sells` (`BarName`, `BeerName`, `Amount`) VALUES
('KrogBar', 'Miller', 3),
('KrogBar', 'Carlsberg', 2),
('KrogBar', 'Heiniken', 1),
('Deluxe', 'Heiniken', 1);
CREATE TABLE `Serves` (
`BarName` varchar(255) NOT NULL DEFAULT '',
`BeerName` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Serves` (`BarName`, `BeerName`) VALUES
('Grace', 'Carlsberg'),
('KrogBar', 'Carlsberg'),
('Deluxe', 'Heiniken'),
('Grace', 'Heiniken'),
('KrogBar', 'Heiniken'),
('KrogBar', 'Miller');
I want to find drinkers that frequent only bars that serve beer that they like (the assumption is that each drinker frequents at least one bar).
How can I construct such a query? I know that I have to use Joins and Sub-queries, I am not new to either of them but all my implementations have not yielded the correct results.
Is this what you looking for;
Select DISTINCT bar.Name,bar.Address,frequents.DrinkerName, likes.BeerName
From
Bar
Join frequents on bar.Name = frequents.BarName
join sells on bar.name = sells.BarName
join likes on frequents.DrinkerName = likes.DrinkerName