MySQL query with optional left join - mysql

i have the following database relations:
user 1:n survey 1:n statement 1:n user_response n:1 user
i need to query all statements which don't have a relation to a user_response or where the field user_response.closed = 1 of a given user-, and a given statement-id.
I don't really get it...
EDIT
Here's an export of my database. For example i have the survey-id 1 and user-id 1. I need all statements of the survey with the id 1, which don't have a response of the user with the id 1, or where the response of the user is not closed.
So my result should be 'Statement 1' (because user_response.closed = 0) and 'Statement 2' (because the user with id 1 didn't give a response).
CREATE TABLE IF NOT EXISTS `statement` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(64) NOT NULL,
`survey_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `2` (`survey_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `statement` (`id`, `title`, `survey_id`) VALUES
(1, 'Statement 1', 1),
(2, 'Statement 2', 1),
(3, 'Statement 1', 2),
(4, 'Statement 1', 3);
CREATE TABLE IF NOT EXISTS `survey` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(64) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `1` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `survey` (`id`, `title`, `user_id`) VALUES
(1, 'Survey 1', 1),
(2, 'Survey 2', 1),
(3, 'Survey 3', 2);
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `user` (`id`, `name`) VALUES
(1, 'Max'),
(2, 'Peter');
CREATE TABLE IF NOT EXISTS `user_response` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`value` int(3) NOT NULL,
`closed` tinyint(1) NOT NULL,
`statement_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `3` (`statement_id`),
KEY `4` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `user_response` (`id`, `value`, `closed`, `statement_id`, `user_id`) VALUES
(1, 50, 0, 1, 1),
(2, 20, 0, 4, 2);
ALTER TABLE `statement`
ADD CONSTRAINT `2` FOREIGN KEY (`survey_id`) REFERENCES `survey` (`id`),
ADD CONSTRAINT `FK_BBA66ED9A94F7BC` FOREIGN KEY (`survey_id`) REFERENCES `survey` (`id`);
ALTER TABLE `survey`
ADD CONSTRAINT `1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
ADD CONSTRAINT `FK_AD5F9BFC9395C3F3` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);
ALTER TABLE `user_response`
ADD CONSTRAINT `3` FOREIGN KEY (`statement_id`) REFERENCES `statement` (`id`),
ADD CONSTRAINT `4` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);

Related

MySql composite foreign key ON DELETE set null [duplicate]

This question already has an answer here:
Multiple Column Foreign Key: Set single column to Null "ON DELETE" instead of all
(1 answer)
Closed 2 years ago.
Please refer to this SQLFiddle
CREATE TABLE `parent` (
`id` varchar(64) NOT NULL,
`master_id` varchar(64) NOT NULL,
`c1_id` varchar(64) DEFAULT NULL,
`c2_id` varchar(64) DEFAULT NULL,
PRIMARY KEY (`master_id`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `child_1` (
`id` varchar(64) NOT NULL,
`master_id` varchar(64) NOT NULL,
PRIMARY KEY (`master_id`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `child_2` (
`id` varchar(64) NOT NULL,
`master_id` varchar(64) NOT NULL,
PRIMARY KEY (`master_id`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO child_1 (`id`, `master_id`)
VALUES
(1, 'm1');
INSERT INTO child_2 (`id`, `master_id`)
VALUES
(2, 'm2'),
(3, 'm1');
INSERT INTO parent (`id`, `master_id`, `c1_id`, `c2_id`)
VALUES
(4, 'm1', null, null),
(5, 'm1', 1, null),
(6, 'm2', null, 2);
I have multiple tables that have composite Primary Key.
All PK are PRIMARY KEY (master_id, id)
And now I try to add Foreign Keys to these tables.
ALTER TABLE `parent`
ADD CONSTRAINT parent_fk_1
FOREIGN KEY (`master_id`, `c1_id`)
REFERENCES child_1 (`master_id`, `id`)
ON UPDATE CASCADE
ON DELETE SET NULL;
But it throws error Cannot add foreign key constraint.
Here parent.master_id always must stay NOT NULL while c1_id and c2_id can be set to NULL.
Is it possible to achieve this kind of Foreign Key setup?
I found that there is MATCH SIMPLE option that allows composite key to be partial NULL, but how to apply it for ON DELETE SET NULL?
Both referring Column are NOT NULL, so you can't use ON DELETE SET NULL, this violates the NOT NULL
ALTER TABLE `parent`
ADD CONSTRAINT parent_fk_1
FOREIGN KEY (`master_id`, `c1_id`)
REFERENCES child_1 (`master_id`, `id`)
ON UPDATE CASCADE;

MYSQL: Cannot add or update a child row: a foreign key constraint fails Struggling to add user to group of users

i keep struggling to figure out why i cant seem to add users. Is it a database setup issue? or just a syntax issue? Need some guidance.
When trying to simply insert in an existing user_id to and existing room_id i keep getting
Query:
INSERT INTO group_users (room_id, user_id) VALUES(1, 3);
ERROR: Cannot add or update a child row: a foreign key constraint fails
both the user id and the room id exist in the database already. Wondering what i need to do.
for reference here is the database schema:
CREATE TABLE `groups` (
`room_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`room_name` varchar(60) NOT NULL,
PRIMARY KEY (`room_id`),
UNIQUE KEY `room_name` (`room_name`)
)ENGINE=InnoDB;
-- Chatapp.users definition
CREATE TABLE `users` (
`user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(60) NOT NULL,
`language` varchar(32) DEFAULT 'english',
`SocketID` varchar(42) DEFAULT NULL,
`email` varchar(60) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`registered_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`confirmed_email` tinyint(1) NOT NULL DEFAULT '0',
`confirmed_on` datetime DEFAULT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `username` (`username`)
)ENGINE=InnoDB;
-- Chatapp.group_users definition
CREATE TABLE `group_users` (
`room_id` bigint(20) unsigned NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`room_id`,`user_id`),
KEY `group_users_fk2` (`user_id`),
CONSTRAINT `group_users_fk1` FOREIGN KEY (`room_id`) REFERENCES `groups` (`room_id`),
CONSTRAINT `group_users_fk2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)
) ENGINE=InnoDB;
-- Chatapp.messages definition
CREATE TABLE `messages` (
`message_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned DEFAULT NULL,
`message` mediumtext COLLATE utf8mb4_bin,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`message_id`),
KEY `messages_fk1` (`user_id`),
CONSTRAINT `messages_fk1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
If I changed group_id to room_id it's work normally now:
CREATE TABLE `group_users` (
`room_id` bigint(20) unsigned NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`room_id`,`user_id`),
KEY `group_users_fk2` (`user_id`),
CONSTRAINT `group_users_fk1` FOREIGN KEY (`room_id`) REFERENCES `groups` (`room_id`),
CONSTRAINT `group_users_fk2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `users` (`user_id`, `username`, `language`, `SocketID`, `email`, `password`, `registered_on`, `confirmed_email`, `confirmed_on`) VALUES (NULL, 'pavel', 'english', NULL, NULL, NULL, CURRENT_TIMESTAMP, '0', NULL);
INSERT INTO `users` (`user_id`, `username`, `language`, `SocketID`, `email`, `password`, `registered_on`, `confirmed_email`, `confirmed_on`) VALUES (NULL, 'bob', 'english', NULL, NULL, NULL, CURRENT_TIMESTAMP, '0', NULL);
INSERT INTO `groups` (`room_id`, `room_name`) VALUES (NULL, 'room1');
INSERT INTO `groups` (`room_id`, `room_name`) VALUES (NULL, 'room2');
INSERT INTO `group_users` (`room_id`, `user_id`) VALUES ('1', '2');
INSERT INTO `group_users` (`room_id`, `user_id`) VALUES ('1', '1');
result:
+---------+---------+
| room_id | user_id |
+---------+---------+
| 1 | 1 |
| 1 | 2 |
+---------+---------+
Is rooms the same as groups? Note that there is no room_id in groups-table as your constraint suggest.

Composite foreign key updation failed

I am facing the issue in composite foreign key.
I have tried example, and tried with structure change too but still i am not succeed. I have trid in mysql server.
CREATE TABLE `parenttable` (
`ID` int(11) NOT NULL,
`status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `parenttable` (`ID`, `status`) VALUES
(1, 1),
(2, 1),
(3, 1);
ALTER TABLE `parenttable`
ADD PRIMARY KEY (`ID`),
ADD KEY `ID` (`ID`,`status`);
ALTER TABLE `parenttable`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
CREATE TABLE `parenttable2` (
`ID` int(11) NOT NULL,
`status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `parenttable2` (`ID`, `status`) VALUES
(1, 1),
(2, 1),
(3, 1);
ALTER TABLE `parenttable2`
ADD PRIMARY KEY (`ID`),
ADD KEY `ID` (`ID`,`status`);
ALTER TABLE `parenttable2`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
CREATE TABLE `childtable` (
`ID` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`parent_id2` int(11) NOT NULL,
`status` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `childtable` (`ID`, `parent_id`, `parent_id2`, `status`) VALUES
(1, 1, 1, 1),
(3, 1, 1, 1),
(4, 2, 2, 1),
(5, 2, 3, 1),
(6, 1, 1, 1);
ALTER TABLE `childtable`
ADD PRIMARY KEY (`ID`),
ADD KEY `fk_childTable_parent_id` (`parent_id`,`status`),
ADD KEY `fk_childTable_parent_id2` (`parent_id2`,`status`);
ALTER TABLE `childtable`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
ALTER TABLE `childtable`
ADD CONSTRAINT `fk_childTable_parent_id` FOREIGN KEY
(`parent_id`,`status`) REFERENCES `parenttable` (`ID`, `status`) ON DELETE
CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_childTable_parent_id2` FOREIGN KEY
(`parent_id2`,`status`) REFERENCES `parenttable2` (`ID`, `status`) ON DELETE
CASCADE ON UPDATE CASCADE;
COMMIT;
I want to update all child rows "status" when parent is changed and single child "status" row too.
Please give me suggestion. Thank You.

#1062 - Duplicate entry '19' for key 'PRIMARY'

I have the following table in MySQL version 5.5.24
CREATE TABLE IF NOT EXISTS `bookings` (
`booking_id` int(11) NOT NULL ,
`class_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
INSERT INTO `bookings` (`booking_id`, `class_id`, `user_id`) VALUES
(19, 3, 5),
(21, 6, 5);
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL,
`username` varchar(20) NOT NULL,
`firstname` varchar(20) NOT NULL,
`lastname` varchar(20) NOT NULL,
`email` varchar(30) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
INSERT INTO `users` (`user_id`, `username`, `firstname`, `lastname`, `email`, `password`) VALUES
(4, 'another', 'Anne', 'Other', 'another#gmail.com', '1234'),
(5, 'rbirney', 'Rosanne', 'Birney', 'rosanne.birney#gmail.com', '1111');
ALTER TABLE `bookings`
ADD PRIMARY KEY (`booking_id`), ADD KEY `class_id` (`class_id`,`user_id`), ADD KEY `user_id` (`user_id`);
ALTER TABLE `classes`
ADD PRIMARY KEY (`class_id`);
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
ALTER TABLE `bookings`
MODIFY `booking_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=22;
ALTER TABLE `classes`
MODIFY `class_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=11;
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6;
ALTER TABLE `bookings`
ADD CONSTRAINT `fkBookingClass` FOREIGN KEY (`class_id`) REFERENCES `classes` (`class_id`),
ADD CONSTRAINT `fkBookingUser` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`);
I am getting the following message
#1062 - Duplicate entry '19' for key 'PRIMARY'
anyone have any ideas?
In SQL it is not allowed to use the same value for a primary key twice. (value = 19)
Primary keys are always unique.

#1451 - Cannot delete or update a parent row: a foreign key constraint fails

My code SQL is :
enter code here
CREATE TABLE IF NOT EXISTS `participer` (
`statut_Invitation` tinyint(1) NOT NULL,
`NumVersion` int(11) NOT NULL,
`InviteCode` varchar(255) NOT NULL,
`IdQuest` int(11) NOT NULL,
PRIMARY KEY (`NumVersion`,`InviteCode`,`IdQuest`),
KEY `FK_Participer_NumVersion` (`NumVersion`),
KEY `FK_Participer_IdQuest` (`IdQuest`),
KEY `FK_Participer_InviteCode` (`InviteCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `participer` (`statut_Invitation`, `NumVersion`, `InviteCode`, `IdQuest`) VALUES
(0, 2, '2548', 1),
(0, 2, '8742', 1);
CREATE TABLE IF NOT EXISTS `questionnaire` (
`IdQuest` int(11) NOT NULL AUTO_INCREMENT,
`Nom` varchar(256) DEFAULT NULL,
`DateCreation` date DEFAULT NULL
PRIMARY KEY (`IdQuest`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `questionnaire` (`IdQuest`, `Nom`, `DateCreation`, `ID`) VALUES
(1, 'Parions Sport', '2015-03-23'),
(2, 'GPS', '2015-03-23');
CREATE TABLE IF NOT EXISTS `utilisateurs` (
`InviteCode` varchar(255) NOT NULL,
`Email` varchar(25) NOT NULL,
`DateNaissance` date DEFAULT NULL,
`Ville` varchar(25) DEFAULT NULL,
PRIMARY KEY (`InviteCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `utilisateurs` (`InviteCode`, `Email`, `DateNaissance`, `Ville`) VALUES
('1235314', 'bocchi#gmail.com', NULL, NULL),
('2548', 'bocchiTEST#gmail.com', NULL, NULL),
('337752493652424404824466004444846460026', 'dylan#gmail.com', NULL, NULL),
('53131172170670664482420846024208824402', 'dylan2#gmail.com', NULL, NULL),
('5446544', 'lool', NULL, NULL),
('8742', 'max#gmail.com', NULL, NULL);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `versionquestionnaire` (
`NumVersion` int(11) NOT NULL,
`DateExpiration` date DEFAULT NULL,
`SommeNote` float DEFAULT NULL,
`NbReponses` int(11) DEFAULT NULL,
`IdQuest` int(11) NOT NULL,
PRIMARY KEY (`NumVersion`,`IdQuest`),
KEY `FK_VersionQuestionnaire_IdQuest` (`IdQuest`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `versionquestionnaire` (`NumVersion`, `DateExpiration`, `SommeNote`, `NbReponses`, `IdQuest`) VALUES
(1, '2015-03-26', 120, 2, 1),
(1, '2015-03-30', 100, 1, 2),
(2, '2015-03-26', 210, 3, 1),
(2, '2015-03-30', 300, 4, 2);
ALTER TABLE `participer`
ADD CONSTRAINT `FK_Participer_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `versionquestionnaire` (`IdQuest`),
ADD CONSTRAINT `FK_Participer_InviteCode` FOREIGN KEY (`InviteCode`) REFERENCES `utilisateurs` (`InviteCode`),
ADD CONSTRAINT `FK_Participer_NumVersion` FOREIGN KEY (`NumVersion`) REFERENCES `versionquestionnaire` (`NumVersion`);
ALTER TABLE `versionquestionnaire`
ADD CONSTRAINT `FK_VersionQuestionnaire_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `questionnaire` (`IdQuest`);
When i want to delete the version 1 of the questionnaire 1 :
DELETE FROM `versionquestionnaire` WHERE `versionquestionnaire`.`NumVersion` = 1 AND `versionquestionnaire`.`IdQuest` = 1;
I have a error :
1451 - Cannot delete or update a parent row: a foreign key constraint fails (`testbug`.`participer`, CONSTRAINT `FK_Participer_IdQuest` FOREIGN KEY (`IdQuest`) REFERENCES `versionquestionnaire` (`IdQuest`)) ;
I don't understand because in the table participer, there isn't the couple with NumVersion = 1 and IdQuest = 1, there are 2 couples with NumVersion = 1 and IdQuest = 1. So my request may be run.
In short, you can't delete records from versionquestionnaire because some records in participer table reference records in participer.
Your request clearly violates IdQuest constraint: you're trying to delete a record with IdQuest = 1, while BOTH participants that still reference that ID.