Where is this unknown column in my MYSQL DB? - mysql

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;

Related

error of 1824: failed to open the referenced table

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

Having trouble with creating tables using foreign key [duplicate]

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.

SQL query join condition

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

Error: 150 / MySQL 'Can't create table'

So I made a database model through the model creator in MySQL Workbench. However, I'm running into an error code when I try to convert it to an SQL file. The error says
Can't create table project2i2w.customer (error: 150 "Foreign key constraint is incorrectly formed") 0.032 sec.
Here is my script:
-- 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='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema project2i2w
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `project2i2w` ;
-- -----------------------------------------------------
-- Schema project2i2w
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `project2i2w` DEFAULT CHARACTER SET utf8 ;
USE `project2i2w` ;
-- -----------------------------------------------------
-- Table `project2i2w`.`services`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project2i2w`.`services` (
`service_id` INT NOT NULL AUTO_INCREMENT,
`service_name` VARCHAR(50) NOT NULL,
`service_desc` VARCHAR(250) NOT NULL,
`os_id` INT NOT NULL,
`customer_id` INT NOT NULL,
PRIMARY KEY (`service_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `project2i2w`.`customer`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project2i2w`.`customer` (
`customer_id` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`city` VARCHAR(45) NOT NULL,
`street` VARCHAR(20) NOT NULL,
`province` VARCHAR(30) NOT NULL,
`postal` CHAR(7) NOT NULL,
PRIMARY KEY (`customer_id`),
CONSTRAINT `fk_customer_services`
FOREIGN KEY (`customer_id`)
REFERENCES `project2i2w`.`services` (`customer_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `project2i2w`.`op_sys`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project2i2w`.`op_sys` (
`os_id` INT NOT NULL AUTO_INCREMENT,
`os_name` VARCHAR(25) NOT NULL,
`os_desc` VARCHAR(250) NULL,
`os_ver` VARCHAR(10) NOT NULL,
PRIMARY KEY (`os_id`),
CONSTRAINT `fk_op_sys_services1`
FOREIGN KEY (`os_id`)
REFERENCES `project2i2w`.`services` (`os_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
-- -----------------------------------------------------
-- Data for table `project2i2w`.`services`
-- -----------------------------------------------------
START TRANSACTION;
USE `project2i2w`;
INSERT INTO `project2i2w`.`services` (`service_id`, `service_name`, `service_desc`, `os_id`, `customer_id`) VALUES (1, 'Virus Removal', 'Removing of viruses.', 1, 1);
INSERT INTO `project2i2w`.`services` (`service_id`, `service_name`, `service_desc`, `os_id`, `customer_id`) VALUES (2, 'Tune-up', 'Tuning system performance.', 2, 2);
INSERT INTO `project2i2w`.`services` (`service_id`, `service_name`, `service_desc`, `os_id`, `customer_id`) VALUES (3, 'Rooting', 'Accessing super-user status.', 3, 3);
INSERT INTO `project2i2w`.`services` (`service_id`, `service_name`, `service_desc`, `os_id`, `customer_id`) VALUES (4, 'Restore', 'Restoring to stock factory condition.', 4, 4);
INSERT INTO `project2i2w`.`services` (`service_id`, `service_name`, `service_desc`, `os_id`, `customer_id`) VALUES (5, 'Fix Permissions', 'Fixing file permissions.', 5, 5);
COMMIT;
-- -----------------------------------------------------
-- Data for table `project2i2w`.`customer`
-- -----------------------------------------------------
START TRANSACTION;
USE `project2i2w`;
INSERT INTO `project2i2w`.`customer` (`customer_id`, `first_name`, `last_name`, `city`, `street`, `province`, `postal`) VALUES (1, 'Kathryn', 'Trollinger', 'Kanata', '2337 Merivale Road', 'ON', 'K2K 1L9');
INSERT INTO `project2i2w`.`customer` (`customer_id`, `first_name`, `last_name`, `city`, `street`, `province`, `postal`) VALUES (2, 'Lori ', 'Frederick', 'Toronto', '799 Yonge Street', 'ON', 'M4W 1J7');
INSERT INTO `project2i2w`.`customer` (`customer_id`, `first_name`, `last_name`, `city`, `street`, `province`, `postal`) VALUES (3, 'Maxine ', 'Coley', 'Ingersoll', '1305 Albert Street', 'ON', 'N5C 1S2');
INSERT INTO `project2i2w`.`customer` (`customer_id`, `first_name`, `last_name`, `city`, `street`, `province`, `postal`) VALUES (4, 'June ', 'Harrison', 'Windsor', '1089 Goyeau Ave', 'ON', 'N9A 1H9');
INSERT INTO `project2i2w`.`customer` (`customer_id`, `first_name`, `last_name`, `city`, `street`, `province`, `postal`) VALUES (5, 'Joan ', 'Dunn', 'Oshawa', '615 Toy Avenue', 'ON', 'L1H 7M3');
COMMIT;
-- -----------------------------------------------------
-- Data for table `project2i2w`.`op_sys`
-- -----------------------------------------------------
START TRANSACTION;
USE `project2i2w`;
INSERT INTO `project2i2w`.`op_sys` (`os_id`, `os_name`, `os_desc`, `os_ver`) VALUES (1, 'Windows', 'OS by Microsoft', '10');
INSERT INTO `project2i2w`.`op_sys` (`os_id`, `os_name`, `os_desc`, `os_ver`) VALUES (2, 'Mac OSX', 'OS by Apple', 'El Capitan');
INSERT INTO `project2i2w`.`op_sys` (`os_id`, `os_name`, `os_desc`, `os_ver`) VALUES (3, 'Android', 'OS by Google', 'Marshmellow');
INSERT INTO `project2i2w`.`op_sys` (`os_id`, `os_name`, `os_desc`, `os_ver`) VALUES (4, 'iOS', 'OS by Apple', '10');
INSERT INTO `project2i2w`.`op_sys` (`os_id`, `os_name`, `os_desc`, `os_ver`) VALUES (5, 'Linux', 'Open-source OS', 'Ubuntu');
COMMIT;
If someone could fix this for me and tell me why it's not working, I would immensely apreciate it.
Nick
You need some kind of key for customer_id, that will do the trick.
CREATE TABLE IF NOT EXISTS `project2i2w`.`services` (
`service_id` INT NOT NULL AUTO_INCREMENT,
`service_name` VARCHAR(50) NOT NULL,
`service_desc` VARCHAR(250) NOT NULL,
`os_id` INT NOT NULL,
`customer_id` INT NOT NULL,
INDEX `customerid` (`customer_id`),
PRIMARY KEY (`service_id`))
ENGINE = InnoDB;
-- Table project2i2w.customer
CREATE TABLE IF NOT EXISTS `project2i2w`.`customer` (
`customer_id` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`city` VARCHAR(45) NOT NULL,
`street` VARCHAR(20) NOT NULL,
`province` VARCHAR(30) NOT NULL,
`postal` CHAR(7) NOT NULL,
PRIMARY KEY (`customer_id`),
CONSTRAINT `fk_customer_services`
FOREIGN KEY (`customer_id`)
REFERENCES `project2i2w`.`services` (`customer_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Try this
Try this:
CREATE TABLE IF NOT EXISTS `project2i2w`.`services` (
`service_id` INT NOT NULL AUTO_INCREMENT,
`service_name` VARCHAR(50) NOT NULL,
`service_desc` VARCHAR(250) NOT NULL,
`os_id` INT NOT NULL,
PRIMARY KEY (`service_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `project2i2w`.`customer` (
`customer_id` INT NOT NULL AUTO_INCREMENT,
`services_id` INT NOT NULL,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`city` VARCHAR(45) NOT NULL,
`street` VARCHAR(20) NOT NULL,
`province` VARCHAR(30) NOT NULL,
`postal` CHAR(7) NOT NULL,
PRIMARY KEY (`customer_id`),
CONSTRAINT `fk_customer_services`
FOREIGN KEY (`services_id`)
REFERENCES `project2i2w`.`services` (`service_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
The foreign key must be primary key of reference table.

MySQL Query with possable empty values on join

I am not very "brilliant" when it comes to more serious MySQL queries than usual. So some help much needed.
I have a tables as follows:
CREATE TABLE IF NOT EXISTS `clients` (
`c_id` int(11) NOT NULL AUTO_INCREMENT,
`c_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`c_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
INSERT INTO `clients` (`c_name`) VALUES ('client1');
INSERT INTO `clients` (`c_name`) VALUES ('client2');
INSERT INTO `clients` (`c_name`) VALUES ('client3');
INSERT INTO `clients` (`c_name`) VALUES ('client4');
INSERT INTO `clients` (`c_name`) VALUES ('client5');
CREATE TABLE IF NOT EXISTS `people` (
`p_id` int(11) NOT NULL AUTO_INCREMENT,
`p_mark` int(1) NOT NULL DEFAULT '0',
`p_client_id` int(11) DEFAULT NULL,
`p_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`p_source` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '--',
`p_segment` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '--',
`p_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`p_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('0','1','John','AA','3',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('0','2','Alex','BB','23',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('1','4','Ivan','-','-',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('0','4','Stan','FF','5',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('1','1','Paul','DD','12',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('1','4','Greg','-','-',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('0','1','Eric','EE','7',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('1','5','Thom','BB','92',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('0','4','Finn','BB','41',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('0','2','Leon','CC','21',NOW());
INSERT INTO `people` (`p_mark`,`p_client_id`,`p_name`,`p_source`,`p_segment`,`p_date`) VALUES ('1','2','Sean','AA','25',NOW());
CREATE TABLE IF NOT EXISTS `sources` (
`src_id` int(11) NOT NULL AUTO_INCREMENT,
`src_name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`src_abbr` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`src_client` int(11) NOT NULL,
PRIMARY KEY (`src_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Aoo oo','AA',1);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Boo oo','BB',2);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Boo oo','BB',4);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Coo oo','CC',1);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Doo oo','DD',1);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Eoo oo','EE',4);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Foo oo','FF',5);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Aoo oo','AA',2);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Boo oo','BB',5);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Coo oo','CC',2);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Doo oo','DD',4);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Eoo oo','EE',1);
INSERT INTO `sources` (`src_name`,`src_abbr`,`src_client`) VALUES ('Foo oo','FF',4);
CREATE TABLE IF NOT EXISTS `segments` (
`seg_id` int(11) NOT NULL AUTO_INCREMENT,
`seg_client_id` int(11) NOT NULL,
`seg_src_id` int(11) NOT NULL,
`seg_number` int(11) NOT NULL,
`seg_value` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`seg_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','1','3','aa-Seg-c1');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('0','2','23','bb-Seg-c2');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','4','5','ff-Seg-c4');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','1','12','dd-Seg-c1');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','1','7','ee-Seg-c1');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','5','92','bb-Seg-c5');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','4','41','bb-Seg-c4');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','2','21','cc-Seg-c2');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','2','25','aa-Seg-c2');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','3','35','tt-Seg-c3');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','3','11','rr-Seg-c3');
INSERT INTO `segments` (`seg_client_id`,`seg_src_id`,`seg_number`,`seg_value`) VALUES ('1','5','7','zz-Seg-c5');
I am trying to select all rows from people limited by p_client_id 4 with the following query:
SELECT
`people`.*
`clients`.*,
`sources`.*,
`segments`.*
FROM
`people`
INNER JOIN
`clients` ON `people`.`p_client_id` = `clients`.`c_id`
LEFT JOIN
`sources` ON `people`.`p_source` = `sources`.`src_abbr`
RIGHT JOIN
`segments` ON `people`.`p_segment` = `segments`.`seg_number`
WHERE
`p_client_id` = '4'
GROUP BY
`people`.`p_id`
ORDER BY `people`.`p_date` DESC;
The thing is, that the mentioned query suppose to return 4 rows, but the join fails to return rows where people.p_source and people.p_segment are missing.
Any advice is highly appreciated!
Also prepared sqlfiddle: http://sqlfiddle.com/#!2/0c54c/1
Change the join with segments from a RIGHT JOIN to a LEFT JOIN. A RIGHT JOIN includes only the matching rows from the right-hand table of the join (segments).