Duplicate Primary Key Entry - mysql

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

Related

Can not add foreign key in mySQL [duplicate]

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

MySQL custom order by another table

http://sqlfiddle.com/#!9/d865cf/2/1
Schema:
CREATE TABLE IF NOT EXISTS `letters` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`letter` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `letters` (`id`, `letter`) VALUES
(1, 'd'),
(2, 'f'),
(3, 'a'),
(4, 'e'),
(5, 'c'),
(6, 'b');
CREATE TABLE IF NOT EXISTS `sort` (
`next` int(11) NOT NULL,
`prev` int(11) DEFAULT NULL,
PRIMARY KEY (`next`),
UNIQUE KEY `prev` (`prev`),
CONSTRAINT `fk` FOREIGN KEY (`next`) REFERENCES `letters` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
INSERT INTO `sort` (`next`, `prev`) VALUES
(3, NULL),
(4, 1),
(6, 3),
(2, 4),
(1, 5),
(5, 6);
If I run now select letter from letters I get the order d,f,a,e,c,b but I want to get the alphabetical order a,b,c,d,e,f not with the help of order by letter but by using the sort table. If you look at the entries in sort table, a with id=3 is first because next=3 and prev is null then b with id=6 is second because next=6 and prev=3, then c with id=5 is third because next=5 and prev=6, etc.
How can I do a custom order using another table in MySQL?
UPDATE
I did it and it may be the only way to do this in mysql:
DELIMITER //
CREATE PROCEDURE `custom_select`()
begin
declare v_next int;
declare v_letter char(1);
declare v_count tinyint;
DROP TEMPORARY TABLE IF EXISTS temp;
CREATE TEMPORARY TABLE temp (id int,letter char(1),idx int AUTO_INCREMENT,PRIMARY KEY (idx));
select id,letter,count(*) into v_next,v_letter,v_count from letters where sort=0;
while v_next is not null do
insert into temp(id,letter)values(v_next,v_letter);
select id,letter,count(*) into v_next,v_letter,v_count from letters where sort=v_next;
end while;
select id,letter from temp order by idx;
end//
DELIMITER ;
CREATE TABLE IF NOT EXISTS `letters` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`letter` char(1) DEFAULT NULL,
`sort` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `sort` (`sort`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
DELETE FROM `letters`;
INSERT INTO `letters` (`id`, `letter`, `sort`) VALUES
(1, 'd', 5),
(2, 'f', 4),
(3, 'a', 0),
(4, 'e', 1),
(5, 'c', 6),
(6, 'b', 3);
Then i get a,b,c,d,e,f as expected with:
CALL custom_select

what is the best query for tags and other related table

I want to build a query to be suitable for searching in the book.title and the tag.tag
I also want a suitable for counting rows for search query for pagination
Here is my db schema and data
-- Table structure for table `book`
CREATE TABLE IF NOT EXISTS `book` (
`book_id` int(11) NOT NULL,
`title` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
ALTER TABLE `book`
ADD PRIMARY KEY (`book_id`);
-- Dumping data for table `book`
INSERT INTO `book` (`book_id`, `title`) VALUES
(1, 'Alice Journey'),
(2, 'Rody Journey'),
(3, 'My Journey to Amsterdam'),
(4, 'How to train your ketty'),
(5, 'The red fox');
-- --------------------------------------------------------
-- Table structure for table `tag`
CREATE TABLE IF NOT EXISTS `tag` (
`tag_id` int(11) NOT NULL,
`tag` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
ALTER TABLE `tag`
ADD PRIMARY KEY (`tag_id`);
-- Dumping data for table `tag`
INSERT INTO `tag` (`tag_id`, `tag`) VALUES
(1, 'pets'),
(2, 'tale'),
(3, 'Journey');
-- --------------------------------------------------------
-- Table structure for table `tag_book`
CREATE TABLE IF NOT EXISTS `tag_book` (
`tag_id` int(11) NOT NULL,
`book_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tag_book`
ADD PRIMARY KEY (`tag_id`,`book_id`);
-- Dumping data for table `tag_book`
INSERT INTO `tag_book` (`tag_id`, `book_id`) VALUES
(1, 4),
(2, 1),
(2, 2),
(2, 5),
(3, 1),
(3, 2),
(3, 3);
search = 'rody' // exists in book table
search = 'pets' // exists in tag tab
search = 'journey' // exists in book and tag tables
thanks

Calculate value based on sub squery in Trigger

I want to create a trigger in MySql to insert some values in table A and if the record already exist I want to re-calculate one of the fields but I'm keep getting a syntax error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'P1
INNER JOIN
(
SELECT SUM(ATS) AS TOTAGAINST, TOURNID, HOMETEAM, ROUNDID' at line 6
Here's my code (stripped for debugging):
DROP TRIGGER IF EXISTS `trig_matches_insert`;
DELIMITER //
CREATE TRIGGER `trig_matches_insert` AFTER INSERT ON `matches`
FOR EACH ROW
BEGIN
INSERT INTO positions (TEAMID, SC_AGAINST, SC_FOR, ROUNDID, TOURNID) values
(new.HOMETEAM, new.ATS, new.HTS, new.ROUNDID, new.TOURNID)
ON DUPLICATE KEY
UPDATE positions P1
INNER JOIN
(
SELECT SUM(ATS) AS TOTAGAINST, TOURNID, HOMETEAM, ROUNDID FROM matches GROUP BY
TOURNID,HOMETEAM, ROUNDID
) P2 ON P2.HOMETEAM = P1.TEAMID AND P2.TOURNID = P1.TOURNID AND P2.ROUNDID = P1.ROUNDID
SET P1.SC_AGAINST = P2.TOTAGAINST WHERE P1.ID = 10;
END
//
DELIMITER ;
I can't tell what's wrong here..
When I run the update query stand-alone it runs fine
Here's some supporting sql:
CREATE TABLE IF NOT EXISTS `matches` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TOURNID` int(11) NOT NULL,
`HOMETEAM` int(11) NOT NULL,
`AWAYTEAM` int(11) NOT NULL,
`HTS` decimal(10,0) NOT NULL,
`ATS` decimal(10,0) NOT NULL,
`FIELD` text NOT NULL,
`TIME` datetime NOT NULL,
`ROUNDID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `TOURNID` (`TOURNID`),
KEY `HOMETEAM` (`HOMETEAM`),
KEY `AWAYTEAM` (`AWAYTEAM`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;
INSERT INTO `matches` (`ID`, `TOURNID`, `HOMETEAM`, `AWAYTEAM`, `HTS`, `ATS`, `FIELD`, `TIME`, `ROUNDID`) VALUES
(17, 1, 30, 31, '2', '3', '', '2015-01-04 00:00:00', 1),
(18, 1, 30, 3, '2', '4', '', '2015-01-04 00:00:00', 1),
(19, 1, 30, 4, '3', '5', '', '2015-01-04 00:00:00', 1);
CREATE TABLE IF NOT EXISTS `positions` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TOURNID` int(11) NOT NULL,
`TEAMID` int(11) NOT NULL,
`ROUNDID` int(11) NOT NULL,
`SC_FOR` decimal(10,0) NOT NULL,
`SC_AGAINST` decimal(10,0) NOT NULL,
`POULEID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `TOURNID_2` (`TOURNID`,`TEAMID`,`ROUNDID`),
KEY `TOURNID` (`TOURNID`,`TEAMID`),
KEY `TEAMID` (`TEAMID`),
KEY `ROUND` (`ROUNDID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;
INSERT INTO `positions` (`ID`, `TOURNID`, `TEAMID`, `ROUNDID`, `SC_FOR`, `SC_AGAINST`, `POULEID`) VALUES
(10, 1, 30, 1, '2', '12', 0);
Thanks in advance
Mike
Think I've found it, looks like after ON DUPLICATE KEY the positions table already got scope no need to build and update statement from scratch, seems like a quick select will do just fine:
DROP TRIGGER IF EXISTS `matches_after_ins_trig`;
DELIMITER //
CREATE TRIGGER `matches_after_ins_trig` AFTER INSERT ON `matches`
FOR EACH ROW
BEGIN
INSERT INTO positions (TEAMID, SC_AGAINST, SC_FOR, ROUNDID, TOURNID) values (new.HOMETEAM, new.ATS, new.HTS, new.ROUNDID, new.TOURNID)
ON DUPLICATE KEY UPDATE SC_AGAINST = (SELECT SUM(ATS) FROM matches WHERE
matches.HOMETEAM = new.HOMETEAM AND matches.TOURNID = new.TOURNID AND
matches.ROUNDID = new.ROUNDID GROUP BY TOURNID,HOMETEAM, ROUNDID);
END

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.