Can not add foreign key in mySQL [duplicate] - mysql

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

Related

Duplicate Primary Key Entry

I am trying to create 2 tables for poll and poll answers using the following SQL. I am getting the error "Duplicate entry '1' for key 'PRIMARY". Any help is appreciated.
CREATE DATABASE IF NOT EXISTS `phppoll` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `phppoll`;
CREATE TABLE IF NOT EXISTS `polls` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text NOT NULL,
`desc` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `polls` (`id`, `title`, `desc`) VALUES (1, 'What''s your favorite way to browse?', '');
INSERT INTO `polls` (`id`, `title`, `desc`) VALUES (2, 'What''s your favorite way to use tech?', '');
CREATE TABLE IF NOT EXISTS `poll_answers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`poll_id` int(11) NOT NULL,
`title` text NOT NULL,
`votes` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `poll_answers` (`id`, `poll_id`, `title`, `votes`) VALUES (1, 1, 'Laptop', 0), (2, 1, 'Desktop', 0), (3, 1, 'Tablet', 0), (4, 1, 'Other', 0);
INSERT INTO `poll_answers` (`id`, `poll_id`, `title`, `votes`) VALUES (2, 1, 'Laptop', 0), (2, 2, 'Desktop', 0), (2, 3, 'Tablet', 0), (2, 4, 'Other', 0);
As I point out in my comment, your code is fine.
Your problem is probably due to CREATE TABLE IF NOT EXISTS.
You are probably running the code multiple times, and the table is not replaced the second time. What you want instead is DROP TABLE IF EXISTS.
i think if you try INSERT IGNORE it may help you, go here for more details:
(https://www.mysqltutorial.org/mysql-insert-ignore/)

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.

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.

MySQL query with optional left join

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`);

MySQL statement to find data in two tables

I suck at doing joins in MySQL, and I'm pretty sure this is what I need to make this work (though correct me if I'm wrong).
So I have two tables. Here's the SQL to set-up a simple database:
CREATE TABLE IF NOT EXISTS `wp_usermeta` (
`umeta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`meta_key` varchar(255) DEFAULT NULL,
`meta_value` longtext,
PRIMARY KEY (`umeta_id`),
KEY `user_id` (`user_id`),
KEY `meta_key` (`meta_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES
(1, 1, 'first_name', 'David'),
(2, 1, 'last_name', 'Jones'),
(3, 1, 'nickname', 'david'),
(4, 1, 'newsletter', '1'),
(5, 2, 'first_name', 'Greg'),
(6, 2, 'last_name', 'Smith'),
(7, 2, 'nickname', 'greg'),
(8, 2, 'newsletter', '0');
CREATE TABLE IF NOT EXISTS `wp_users` (
`ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_login` varchar(60) NOT NULL DEFAULT '',
`user_pass` varchar(64) NOT NULL DEFAULT '',
`user_nicename` varchar(50) NOT NULL DEFAULT '',
`user_email` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`ID`),
KEY `user_login_key` (`user_login`),
KEY `user_nicename` (`user_nicename`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`) VALUES
(1, 'david', '$^*#NNR&Y&)Mn9emfdfsdfsdfsd', 'david', 'david#domain.com'),
(2, 'greg', 'fdfsdfsdfsd$^*#NNR&Y&)Mn9em', 'greg', 'greg#domain.com');
...and I need to write a statement for a basic page that simply finds the users who have subscribed to the newsletter (meta_key with a meta_value of 1) and displays their first_name and user_email.
Thanks in advance.
It takes a fairly simple join;
SELECT user_login FROM wp_users
JOIN wp_usermeta
ON wp_users.id=wp_usermeta.user_id
WHERE meta_key='newsletter'
AND meta_value=1;
SQLfiddle to play with.