How to perform MySQL UPSERT - php

This is how my table looks like.
CREATE TABLE `answers` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`basicinfo_id` INT(11) NOT NULL,
`question_id` INT(11) NOT NULL,
`answer` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `question_id` (`question_id`),
INDEX `basicinfo_id` (`basicinfo_id`),
CONSTRAINT `basicinfo_id` FOREIGN KEY (`basicinfo_id`) REFERENCES `basic_info` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT `question_id` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=3383;
This is how the data can look like
I want to update the answers if they already exist for "basicinfo_id".
OR
If I change the answer for question_id 1, 2 and 3. How can i upsert the data.?
I have tried this query but it doesn't update the result.
INSERT INTO answers (basicinfo_id, question_id, answer) VALUES('98', 1, '1'),('98', 2, '1'),('98', 3, '1'),('98', 4, '1'),('98', 5, '1') ON DUPLICATE KEY UPDATE basicinfo_id = 98;
I have defined a composite unique key now and this is how it looks like but it still didn't work.
CREATE TABLE `answers` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`basicinfo_id` INT(11) NOT NULL,
`question_id` INT(11) NOT NULL,
`answer` INT(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `basicinfo_id_question_id` (`basicinfo_id`, `question_id`),
INDEX `question_id` (`question_id`),
INDEX `basicinfo_id` (`basicinfo_id`),
CONSTRAINT `basicinfo_id` FOREIGN KEY (`basicinfo_id`) REFERENCES `basic_info` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT `question_id` FOREIGN KEY (`question_id`) REFERENCES `questions` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=3718;

Your ON DUPLICATE KEY UPDATE basicinfo_id = 98; is malformed
Try this :
ON DUPLICATE KEY UPDATE 'answer' = VALUES('answer');
If a unique key already exists it will update the answer field

Related

Unable to create foreign key in PHPmyadmin

I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work

MYSQL #1136 - Column count doesn't match value count at row 1 though they are equal

I keep getting the following error though no. of columns and no. of values match, so I wonder can someone help ?
INSERT INTO `user_dates` (`id`, `date`, `user_id`) VALUES(26545, '2016-04-28', 35);
My Table structure is:
CREATE TABLE `user_dates` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `user_dates_user_id_foreign` (`user_id`),
CONSTRAINT `user_dates_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10459 DEFAULT CHARSET=utf8;

How to insert data into 3 tables?

I have 3 tables called book , author, publisher. The relationship between book and author is a resolving table called book_author_link. The main issue is that when a user adds a book, it was not successfully added as some of the fields belonged in multiple tables. Therefore I am currently having trouble with the INSERT query. How do I go about doing this?
Here is my PHP:
$queryInsert = "INSERT INTO book,author,
publishers(title,isbn,author_name,publisher_name,year_published, book_desc,genre_id,keywords)
FROM book b, author a ,book_author_link ba, publishers p
VALUES ('$title',$isbn,'$author_name','$publisher_name',$year_published,'$genre_type','‌​$book_desc','$genre_id','$keywords')
WHERE b.book_id = ba.book_id AND a.author_id = ba.author_id AND b.publisher_id = p.publisher_id";
Here is my book table:
CREATE TABLE IF NOT EXISTS `fyp`.`book` (
`book_id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(45) NOT NULL,
`ISBN` VARCHAR(45) NOT NULL,
`book_desc` VARCHAR(100) NOT NULL,
`year_published` VARCHAR(45) NOT NULL,
`year_of_birth` YEAR NOT NULL,
`image` VARCHAR(45) NULL,
`genre_id` INT NOT NULL,
`publisher_id` INT NOT NULL,
`user_id` INT NOT NULL,
PRIMARY KEY (`book_id`),
INDEX `fk_book_publishers1_idx` (`publisher_id` ASC),
INDEX `fk_book_user1_idx` (`user_id` ASC),
INDEX `fk_book_genre1_idx` (`genre_id` ASC),
CONSTRAINT `book_publishers_key`
FOREIGN KEY (`publisher_id`)
REFERENCES `fyp`.`publishers` (`publisher_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `book_user_key`
FOREIGN KEY (`user_id`)
REFERENCES `fyp`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `book_genre_key`
FOREIGN KEY (`genre_id`)
REFERENCES `fyp`.`genre` (`genre_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- Table fyp.author
CREATE TABLE IF NOT EXISTS `fyp`.`author` (
`author_id` INT NOT NULL AUTO_INCREMENT,
`author_name` VARCHAR(45) NOT NULL,
`year_of_birth` YEAR NOT NULL,
`year_deceased` YEAR NULL,
`image` VARCHAR(45) NULL,
`user_id` INT NOT NULL,
`country_id` INT NOT NULL,
`gender_id` INT NOT NULL,
PRIMARY KEY (`author_id`),
INDEX `fk_author_user1_idx` (`user_id` ASC),
INDEX `fk_author_country1_idx` (`country_id` ASC),
INDEX `fk_author_gender1_idx` (`gender_id` ASC),
CONSTRAINT `author_user_key`
FOREIGN KEY (`user_id`)
REFERENCES `fyp`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `author_country_key`
FOREIGN KEY (`country_id`)
REFERENCES `fyp`.`country` (`country_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `author_gender_key`
FOREIGN KEY (`gender_id`)
REFERENCES `fyp`.`gender` (`gender_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- Table fyp.publishers
DROP TABLE IF EXISTS `fyp`.`publishers` ;
CREATE TABLE IF NOT EXISTS `fyp`.`publishers` (
`publisher_id` INT NOT NULL,
`publisher_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`publisher_id`))
ENGINE = InnoDB;
-- Table fyp.book_author_link
DROP TABLE IF EXISTS fyp.book_author_link ;
CREATE TABLE IF NOT EXISTS `fyp`.`book_author_link` (
`book_author_link_id` INT NOT NULL AUTO_INCREMENT,
`book_id` INT NOT NULL,
`author_id` INT NOT NULL,
PRIMARY KEY (`book_author_link_id`),
INDEX `fk_book_author_link_book_idx` (`book_id` ASC),
INDEX `fk_book_author_link_author1_idx` (`author_id` ASC),
CONSTRAINT `book_key`
FOREIGN KEY (`book_id`)
REFERENCES `fyp`.`book` (`book_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `author_key`
FOREIGN KEY (`author_id`)
REFERENCES `fyp`.`author` (`author_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I recommend running the queries in a transaction: http://php.net/manual/pdo.transactions.php
Also, you might need this to get the AUTO_INCREMENT id: http://php.net/manual/de/pdo.lastinsertid.php
Are you using phpMyAdmin as GUI? Have you tried running your SQL there? If there is a "relationship issue", it should print the exact error message. You should provide it here.
you could give a try to a trigger AFTER INSERT on the main table.

MYSQL multiple join error and learning

I appreciate your patience as I am still trying to learn joining tables. I have in the past done joins between two tables, and I would nest them in the php code which I am sure is incorrect and very inefficient. I would like to learn the "right" way.
Here is my query so far. I am getting an error: unknown column in on clause
SELECT PermissionID FROM Permissions
INNER JOIN PermissionsAssigned ON Permissions.PermissionID = PermissionsAssigned.PermissionID
INNER JOIN Roles ON PermissionsAssigned.RoleID = Roles.RoleID
INNER JOIN RolesAssigned ON Roles.RoleID = RolesAssigned.RoleID
INNER JOIN UserDirectory ON RolesAssigned.UserID = UserDirectory.UserID
WHERE UserDirectory.UserID = 4
CREATE TABLE IF NOT EXISTS `Permissions` (
`PermissionID` int(11) NOT NULL AUTO_INCREMENT,
`Description` tinytext NOT NULL,
PRIMARY KEY (`PermissionID`),
UNIQUE KEY `ID_UNIQUE` (`PermissionID`),
KEY `Index 1` (`PermissionID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `PermissionsAssigned` (
`PermissionsAssignedID` int(11) NOT NULL AUTO_INCREMENT,
`Permission ID` int(11) NOT NULL DEFAULT '0',
`RoleID` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`PermissionsAssignedID`),
UNIQUE KEY `PermissionsAssignedID_UNIQUE` (`PermissionsAssignedID`),
KEY `FK_PermissionsAssigned_Permissions` (`Permission ID`),
KEY `FK_PermissionsAssigned_Roles` (`RoleID`),
KEY `Index 1` (`PermissionsAssignedID`),
CONSTRAINT `FK_PermissionsAssigned_Permissions` FOREIGN KEY (`Permission ID`) REFERENCES `Permissions` (`PermissionID`),
CONSTRAINT `FK_PermissionsAssigned_Roles` FOREIGN KEY (`RoleID`) REFERENCES `Roles` (`RoleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `Roles` (
`RoleID` int(11) NOT NULL AUTO_INCREMENT,
`Description` tinytext NOT NULL,
PRIMARY KEY (`RoleID`),
UNIQUE KEY `ID_UNIQUE` (`RoleID`),
KEY `Index 1` (`RoleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `RolesAssigned` (
`RoleAssignedID` int(11) NOT NULL AUTO_INCREMENT,
`UserID` int(11) NOT NULL,
`RoleID` int(11) NOT NULL,
PRIMARY KEY (`RoleAssignedID`),
UNIQUE KEY `ID_UNIQUE` (`RoleAssignedID`),
KEY `Index 1` (`RoleAssignedID`),
KEY `FK_RolesAssigned_UserDirectory` (`UserID`),
KEY `FK_RolesAssigned_Roles` (`RoleID`),
CONSTRAINT `FK_RolesAssigned_Roles` FOREIGN KEY (`RoleID`) REFERENCES `Roles` (`RoleID`),
CONSTRAINT `FK_RolesAssigned_UserDirectory` FOREIGN KEY (`UserID`) REFERENCES `UserDirectory` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `UserDirectory` (
`UserID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`UserID`),
UNIQUE KEY `UserID_UNIQUE` (`UserID`),
KEY `Index 1` (`UserID`),
KEY `FK_UserDirectory_Departments` (`DepartmentID`),
CONSTRAINT `FK_UserDirectory_Departments` FOREIGN KEY (`DepartmentID`) REFERENCES `Departments` (`DepartmentID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Thanks!
Matthew
CREATE TABLE IF NOT EXISTS `PermissionsAssigned` (
`PermissionsAssignedID` int(11) NOT NULL AUTO_INCREMENT,
***`Permission ID`*** int(11) NOT NULL DEFAULT '0',
HERE is the problem
change Permission ID to PermissionID in you database
You need to make table definition proper like
CREATE TABLE IF NOT EXISTS `PermissionsAssigned` (
`PermissionsAssignedID` int(11) NOT NULL AUTO_INCREMENT,
`PermissionID` int(11) NOT NULL DEFAULT '0'`, .................
PermissionID should be a Whole word . Check in your Code its having space.

ID auto increase but not unique

I have a table that I want to have an id that will auto increase itself but not be primary or unique.
Is this possible?
You should really create another table, in that case.
E.g.
CREATE TABLE `Calls` (
`Id` INT(10) AUTO_INCREMENT,
`From` VARCHAR(100) NOT NULL,
`To` VARCHAR(100) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB;
CREATE TABLE `CallHistory` (
`Id` INT(15) AUTO_INCREMENT,
`CallId` INT(10) NOT NULL,
`Text` VARCHAR(255) NOT NULL,
PRIMARY KEY (`Id`),
KEY `CallHistory_Calls_idx` (`CallId`),
CONSTRAINT `CallHistory_Calls`
FOREIGN KEY (`CallId`)
REFERENCES `calls` (`Id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
Here's a demo on SQLFiddle.
A benefit of this is that if you delete a row from Calls, the rows in CallHistory will also be deleted.
Running this query:
SELECT `Calls`.`Id`,
`Calls`.`From`,
`Calls`.`To`,
`CallHistory`.`Text`
FROM `Calls`, `CallHistory`
WHERE `Calls`.`Id` = `CallHistory`.`CallId`;
Gives results something like this:
This should work:
id int NOT NULL AUTO_INCREMENT
Anyway I don't see how it wouldn't stay unique unless you update existing values later
Yes, you need to set auto_increment constraint:
CREATE TABLE `test` (
`testID` int(11) NOT NULL, //primary key here
`testInc` int(11) NOT NULL AUTO_INCREMENT, //here is your non-primary auto increment column
PRIMARY KEY (`testID`),
KEY `testInc` (`testInc`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
and if you want this to be unique also then you may add unique constraint:
ALTER TABLE `test` ADD CONSTRAINT ux_unique_constraint UNIQUE `testInc`

Categories