Unexpected mysql behavior when inserting new rows - mysql

I've got this query:
INSERT INTO series_measures (sensor_SID,dataset_SID,created_on)
VALUES (841468,145,'2016-10-26 11:36:07'), ... ,(841505,145,'2016-10-26 11:36:07')
ON DUPLICATE KEY UPDATE sensor_SID=VALUES(sensor_SID),dataset_SID=VALUES(dataset_SID),created_on=VALUES(created_on);
Two things that I don't understand are happening here:
A. If (sensor_SID-dataset_SID) is already inserted:
Error:
Duplicate entry '145-841468' for key 'fk_series_meas_dataset_idx'
But ON DUPLICATE KEY UPDATE should avoid that.
B. If (sensor_SID-dataset_SID) is not inserted yet:
Error:
Duplicate entry '412870' for key 'PRIMARY'
PRIMARY is SID, which has auto-increment (see create statement below), so that makes no sense to me.
This is the create statement of the table:
CREATE TABLE `series_measures` (
`SID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sensor_SID` int(10) unsigned NOT NULL,
`dataset_SID` int(10) unsigned NOT NULL,
`created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`SID`),
UNIQUE KEY `fk_series_meas_dataset_idx` (`dataset_SID`,`sensor_SID`),
KEY `fk_series_meas_sensor_idx` (`sensor_SID`),
CONSTRAINT `fk_series_meas_dataset` FOREIGN KEY (`dataset_SID`) REFERENCES `datasets` (`SID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_series_meas_sensor` FOREIGN KEY (`sensor_SID`) REFERENCES `sensors` (`SID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=412908 DEFAULT CHARSET=utf8;

Related

How to cascade delete from same MySQL table

Is it possible to cascade delete from same MySQL table? I want to cascade delete in a table that references itself in relations.
Example:
I have a comments table that has comment_id and parent_id, where parent_id is the same id in comment_id.
Parent_id could be either another comment_id or null if it's a root
comment.
I want to be able to select any node in this tree and delete it. In the process, all child nodes and sub-child nodes should be deleted.
I have tried to alter my table using this query
ALTER TABLE `comment`
ADD FOREIGN KEY (`comment_id`)
REFERENCES `comment`(`parent_id`) ON DELETE CASCADE ON UPDATE RESTRICT;
but I end up with an error
Cannot add or update a child row: a foreign key constraint fails
(zendaya001.#sql-6c1_1044ab, CONSTRAINT comment_ibfk_3 FOREIGN
KEY (comment_id) REFERENCES comment (parent_id) ON DELETE
CASCADE ON UPDATE RESTRICT)
For reproduction, this is my comment table:
CREATE TABLE `comment` (
`comment_id` int NOT NULL,
`post_id` int UNSIGNED NOT NULL,
`user_id` int NOT NULL,
`parent_id` int DEFAULT NULL,
`content` text NOT NULL,
`type` varchar(50) DEFAULT NULL,
`count_replies` int NOT NULL DEFAULT '0',
`count_likes` int NOT NULL DEFAULT '0',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `comment`
--
ALTER TABLE `comment`
ADD PRIMARY KEY (`comment_id`),
ADD KEY `user_id` (`user_id`),
ADD KEY `post_id` (`post_id`),
ADD KEY `parent_id` (`parent_id`);
You try to create the foreign key with incorrect direction.
Must be:
ALTER TABLE `comment`
ADD FOREIGN KEY (`parent_id`)
REFERENCES `comment`(`comment_id`) ON DELETE CASCADE ON UPDATE RESTRICT;
https://dbfiddle.uk/iJRlziwL
comment_id must be defined at least UNIQUE (maybe PRIMARY KEY).
I cannot insert a new record into the table even if ON UPDATE RESTRICT is also set to CASCADE – Freesoul
You do something wrongly.
https://dbfiddle.uk/rcUupB2b

Adding multiple foreign key constraints

I am having trouble adding multiple foreign key constraints to this table. I get an error saying
Foreign key constraint is incorrectly formed
Both id's referenced are primary keys in their respective tables. What am I doing wrong?
CREATE TABLE `works_on` (
`eid` int(11) DEFAULT NULL,
`pid` int(11) DEFAULT NULL,
`start_date` date NOT NULL,
PRIMARY KEY (`eid`, `pid`),
CONSTRAINT `works_on_ibfk_1` FOREIGN KEY (`eid`)
REFERENCES `employee` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `works_on_ibfk_2` FOREIGN KEY (`pid`)
REFERENCES `project` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB
You have a paradox here - you cannot have a primary key where any of the elements has a null values AND therefore you cannot on delete SET NULL..
You should also be seeing an error message telling you that the primary key is invalid..

MySQL throwing duplicate entry on update

I'm trying to update a non-key field on my table, but I keep getting duplicate primary key errors. For what I searched, it's an actual MySQL bug, but I'd like to know if there is a way around it, since so far I can´t update my table at all.
CREATE TABLE `AREA_FOLDER_PERMISSION` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`FOLDER_ID` int(11) NOT NULL,
`COMPANY_AREA_ID` int(11) NOT NULL,
`CAN_READ` bit(1) NOT NULL,
`CAN_WRITE` bit(1) NOT NULL,
`CAN_PRINT` bit(1) NOT NULL,
`CAN_APPROVE` bit(1) NOT NULL,
`CAN_REVIEW` bit(1) NOT NULL,
`CAN_CREATE` bit(1) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `id_UNIQUE` (`ID`),
KEY `FOLDER_ID_idx` (`FOLDER_ID`),
KEY `COMPANY_AREA_ID_idx` (`COMPANY_AREA_ID`),
CONSTRAINT `COMPANY_AREA_ID` FOREIGN KEY (`COMPANY_AREA_ID`) REFERENCES `COMPANY_AREA` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK2g92hsfhocnfsdr57fp7065mv` FOREIGN KEY (`COMPANY_AREA_ID`) REFERENCES `COMPANY_AREA` (`ID`),
CONSTRAINT `FKhisnf7elm60on0mjytiteio2a` FOREIGN KEY (`FOLDER_ID`) REFERENCES `FOLDER` (`ID`),
CONSTRAINT `FOLDER_ID` FOREIGN KEY (`FOLDER_ID`) REFERENCES `FOLDER` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1124828 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
And the error is:
Operation failed: There was an error while applying the SQL script to the database.
Executing:
UPDATE `sgidb`.`AREA_FOLDER_PERMISSION` SET `CAN_PRINT` = '1' WHERE (`ID` = '791063');
ERROR 1062: 1062: Duplicate entry '791063' for key 'id_UNIQUE'
SQL Statement:
UPDATE `sgidb`.`AREA_FOLDER_PERMISSION` SET `CAN_PRINT` = '1' WHERE (`ID` = '791063')

Foreign key Integrity constraint violation: 1452

I've recently started trying to use foreign keys to make database management easier on myself. I'm having a terrible time trying to figure out how they actually work, and most of the time I can get it working between tables without issue. But I'm currently having an issue with 2 of my tables, and I can't figure it out.
I'm getting an error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(REDACTED.rc_logs, CONSTRAINT rc_logs_ibfk_1 FOREIGN
KEY (user_id) REFERENCES rc_teammates (uid) ON DELETE CASCADE ON
UPDATE CASCADE)
[/home5/redacted/public_html/redacted/rc/public/assets/php/connection.php:25]
but my tables seem to be set up properly, and I'm really confused about why it's not working. Here is my table structures:
rc_teammates
CREATE TABLE `rc_teammates` (
`uid` int(11) NOT NULL,
`name` text NOT NULL,
`primary_line` int(11) NOT NULL,
`hireStatus` text NOT NULL,
`created_on` date NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `rc_teammates`
ADD PRIMARY KEY (`uid`), ADD UNIQUE KEY `uid` (`uid`), ADD KEY `primary_line` (`primary_line`), ADD KEY `primary_line_2` (`primary_line`);
ALTER TABLE `rc_teammates`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `rc_teammates`
ADD CONSTRAINT `rc_teammates_ibfk_1` FOREIGN KEY (`primary_line`) REFERENCES `rc_lines` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE;
rc_logs
CREATE TABLE IF NOT EXISTS `rc_logs` (
`uid` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`line` int(11) NOT NULL,
`date` date NOT NULL,
`type` varchar(15) NOT NULL,
`timein` time NOT NULL,
`timeout` time NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=latin1;
ALTER TABLE `rc_logs`
ADD PRIMARY KEY (`uid`), ADD KEY `user_id` (`user_id`), ADD KEY `line` (`line`), ADD KEY `user_id_2` (`user_id`);
ALTER TABLE `rc_logs`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=53;
ALTER TABLE `rc_logs`
ADD CONSTRAINT `rc_logs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `rc_teammates` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `rc_logs_ibfk_2` FOREIGN KEY (`line`) REFERENCES `rc_lines` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE;
I've tried to look up the error, and I've had this issue before but I do not remember how I solved it. What's worse is, this was working earlier, until I emptied the rc_teammates table to start fresh.
I really cannot figure this out, and would love any pointers. Thanks!
As you said you have "emptied" (TRUNCATE?) the table rc_teammates.
And you try to insert a record in rc_logs, and this record has a user_id that doesn't exists in rc_teammates, thus violation of the following constraint:
ADD CONSTRAINT `rc_logs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `rc_teammates` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE
Just add a record in rc_teammates, having a uid equal to the user_id of the record you are trying to insert in rc_logs, and retry.
Also, about this :
ALTER TABLE `rc_teammates`
ADD PRIMARY KEY (`uid`), ADD UNIQUE KEY `uid` (`uid`),
ALTER TABLE `rc_teammates`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;
When you set a column as PRIMARY KEY, it is de facto : UNIQUE, NOT NULL and INDEXED. You don't need to specify all this, PRIMARY KEY is enough. This is valid for your other table as well.

MySQL primary key column is not unique?

I have the following table in a MySQL database:
CREATE TABLE `datavalues` (
`ValueID` int(11) NOT NULL AUTO_INCREMENT,
`DataValue` double NOT NULL,
`ValueAccuracy` double DEFAULT NULL,
`LocalDateTime` datetime NOT NULL,
`UTCOffset` double NOT NULL,
`DateTimeUTC` datetime NOT NULL,
`SiteID` int(11) NOT NULL,
`VariableID` int(11) NOT NULL,
`OffsetValue` double DEFAULT NULL,
`OffsetTypeID` int(11) DEFAULT NULL,
`CensorCode` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'nc',
`QualifierID` int(11) DEFAULT NULL,
`MethodID` int(11) NOT NULL DEFAULT '0',
`SourceID` int(11) NOT NULL,
`SampleID` int(11) DEFAULT NULL,
`DerivedFromID` int(11) DEFAULT NULL,
`QualityControlLevelID` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`ValueID`),
UNIQUE KEY `DataValues_UNIQUE_DataValues` (`DataValue`,`ValueAccuracy`,`LocalDateTime`,`UTCOffset`,`DateTimeUTC`,`SiteID`,`VariableID`,`OffsetValue`,`OffsetTypeID`,`CensorCode`,`QualifierID`,`MethodID`,`SourceID`,`SampleID`,`DerivedFromID`,`QualityControlLevelID`),
KEY `FK_DataValues_Sites` (`SiteID`),
KEY `FK_DataValues_Sources` (`SourceID`),
KEY `FK_DataValues_QualityControlLevels` (`QualityControlLevelID`),
KEY `FK_DataValues_OffsetTypes` (`OffsetTypeID`),
KEY `FK_DataValues_CensorCodeCV` (`CensorCode`),
KEY `FK_DataValues_Variables` (`VariableID`),
KEY `FK_DataValues_Methods` (`MethodID`),
KEY `FK_DataValues_Qualifiers` (`QualifierID`),
KEY `FK_DataValues_Samples` (`SampleID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
ALTER TABLE `datavalues`
ADD CONSTRAINT `FK_DataValues_Sites` FOREIGN KEY (`SiteID`) REFERENCES `sites` (`SiteID`) ON DELETE NO ACTION ON UPDATE CASCADE,
ADD CONSTRAINT `FK_DataValues_Sources` FOREIGN KEY (`SourceID`) REFERENCES `sources` (`SourceID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_QualityControlLevels` FOREIGN KEY (`QualityControlLevelID`) REFERENCES `qualitycontrollevels` (`QualityControlLevelID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_OffsetTypes` FOREIGN KEY (`OffsetTypeID`) REFERENCES `offsettypes` (`OffsetTypeID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_CensorCodeCV` FOREIGN KEY (`CensorCode`) REFERENCES `censorcodecv` (`Term`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Variables` FOREIGN KEY (`VariableID`) REFERENCES `variables` (`VariableID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Methods` FOREIGN KEY (`MethodID`) REFERENCES `methods` (`MethodID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Qualifiers` FOREIGN KEY (`QualifierID`) REFERENCES `qualifiers` (`QualifierID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_DataValues_Samples` FOREIGN KEY (`SampleID`) REFERENCES `samples` (`SampleID`) ON DELETE NO ACTION ON UPDATE NO ACTION;
When I open my database in PhpMyAdmin 4.0.3 and run a query:
SELECT MAX(DateTimeUTC) from `datavalues`
the query executes but PhpMyAdmin shows a
warning:
This table does not contain a unique column. Grid edit, checkbox,
Edit, Copy and Delete features are not available.
How is it possible? I thought that if I have one column with PRIMARY KEY constraint then the column is UNIQUE. Could this be a bug in PhpMyAdmin? I'm confused.
I found the answer: The warning:
This table does not contain a unique column. Grid edit, checkbox,
Edit, Copy and Delete features are not available.
applies to the current result set and not to the original table.
Álvaro G. Vicario's comment is right.
This appears to be a new thing in PhpMyAdmin 4.0.4 and I find this type of message more confusing than useful.
All you got to do is add a unique column like one called id with a index = PRIMARY like the pic, or if you have one already that is called id that are numbers just make it PRIMARY