MySQL Query with possable empty values on join - mysql

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).

Related

Where is this unknown column in my MYSQL DB?

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;

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

Mysql TIMESTAMP trigger doesn't work

What I do wrong?
I have table1
On INSERT data to table1 I have trigger:
BEGIN
INSERT INTO table2 (`c_id`, `date`, `product_id`, `price`)
VALUES (
NEW.c_id,
NEW.date = CURRENT_TIMESTAMP,
NEW.product_id,
NEW.price
); END
CREATE TABLE `table2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`c_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`product_id` int(11) NOT NULL,
`price` decimal(9,2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `c_data` (`c_id`,`date`,`product_id`)
) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=latin1;
As result, I get 0000-00-00 00:00:00 in date
MySQL version 5.6.28
Remove date and NEW.date = CURRENT_TIMESTAMP, from insert query. By default mysql will set date for it.
INSERT INTO table2 (`c_id`, `product_id`, `price`)
VALUES (
NEW.c_id,
NEW.product_id,
NEW.price
);

MySQL - Remove duplicate records entity relationship many to many

As I can get records from multiple tables omitting duplicate, for example I have this table "code attached tables":
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for interests
-- ----------------------------
DROP TABLE IF EXISTS `interests`;
CREATE TABLE `interests` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of interests
-- ----------------------------
INSERT INTO `interests` VALUES ('1', 'Sport');
INSERT INTO `interests` VALUES ('2', 'Technology');
INSERT INTO `interests` VALUES ('3', 'Games');
INSERT INTO `interests` VALUES ('4', 'Security');
INSERT INTO `interests` VALUES ('5', 'Movies');
-- ----------------------------
-- Table structure for interests_has_user
-- ----------------------------
DROP TABLE IF EXISTS `interests_has_user`;
CREATE TABLE `interests_has_user` (
`interests_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`interests_id`,`user_id`),
KEY `fk_interests_has_user_user1_idx` (`user_id`),
KEY `fk_interests_has_user_interests_idx` (`interests_id`),
CONSTRAINT `fk_interests_has_user_interests` FOREIGN KEY (`interests_id`) REFERENCES `interests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_interests_has_user_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of interests_has_user
-- ----------------------------
INSERT INTO `interests_has_user` VALUES ('1', '1');
INSERT INTO `interests_has_user` VALUES ('2', '1');
INSERT INTO `interests_has_user` VALUES ('3', '1');
INSERT INTO `interests_has_user` VALUES ('4', '1');
INSERT INTO `interests_has_user` VALUES ('5', '1');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`country` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'Name', 'email#email.com', '123123', '1', '1', '1');
I need to get records from the table[ user ] and the table[ interests_has_user ], where a user can have many interests at the table table[ interests_has_user ], I'm doing the query this way:
SELECT
user.id,
user.name,
user.email,
user.country,
user.state,
user.city,
interests_has_user.interests_id,
interests_has_user.user_id
FROM
user
LEFT JOIN interests_has_user
ON user.id = interests_has_user.user_id
WHERE user.id = 1;
And I throw all records of the table table[ interests_has_user ], but in all rows the user is repeated, image attached with the result.
Note: What is shaded in yellow should be empty or null fields.
What the best solution for this, use INNER JOIN, or separate consutas.
I appreciate your help, thank you very much.
INNER JOIN will not return users without interests. So it is not what you want.
If you want to lighten-up the query results you could do two queries:
First find out the user details
SELECT
user.id,
user.name,
user.email,
user.country,
user.state,
user.city
FROM
user
WHERE user.id = 1
Then the interests ids.
SELECT user.id, interests_has_user.interests_id, interests_has_user.user_id
FROM user
LEFT JOIN interests_has_user ON user.id = interests_has_user.user_id
WHERE user.id = 1