mysql error 1451 - mysql

I have mysql error with code 1451.
Cannot delete or update a parent row: a foreign key constraint fails (online_store_admin.osa_admin_logs, CONSTRAINT fk_admins_logs FOREIGN KEY (aid) REFERENCES osa_admins (aid))
here sql statement :
drop table if exists osa_admins;
create table if not exists osa_admins(
aid int unsigned not null auto_increment,
uid varchar(50) not null,
pass char(41) not null,
erp_id int unsigned not null,
last_login int unsigned not null,
is_block tinyint unsigned not null,
menus varchar(50) not null,
is_login tinyint unsigned not null,
ip_login char(15) not null,
constraint idx_osa_admins primary key using btree(aid)
);
insert into osa_admins value
(NULL, 'root', password('6789'), '0', '0', '0', '*', '0', '127.000.000.001'),
(NULL, 'ryu', password('6789'), '0', '0', '0', '*', '0', '127.000.000.001');
drop table if exists osa_admin_logs;
create table if not exists osa_admin_logs(
lid bigint unsigned not null,
aid int unsigned not null,
dates int unsigned not null,
logs text not null,
constraint idx_osa_admin_logs primary key using btree(lid),
constraint fk_admins_logs foreign key (aid)
references osa_admins(aid)
match full
on update cascade
on delete cascade
);
insert into osa_admin_logs values
(NULL, '2', '0', 'some action here'),
(NULL, '2', '0', 'again, some action here');
Problem come when i use this statement:
delete from osa_admins where aid='2';
i think i had set "on delete cascade". anyone know how to delete cascade? so i don't necessary to manual detelet osa_admin_logs data. oh, i using innodb as db engine(default mysql that i have).
And sorry i ask same question that had answer, just let me know where i can get my question.
Thank You.

Use the following commands to do this:
SET foreign_key_checks = 0;
DELETE FROM your_table_name WHERE your_condition;
SET foreign_key_checks = 1;

remove the match full from the constraint
Use of an explicit MATCH clause will
not have the specified effect, and
also causes ON DELETE and ON UPDATE
clauses to be ignored. For these
reasons, specifying MATCH should be
avoided.
MySql docs https://dev.mysql.com/doc/refman/8.0/en/create-table.html

Related

Foreign key constraint fails but referenced row exists

I'm running MySQL 5.7.21 on Amazon RDS.
I know this question has been asked a thousand times, but I'm getting the issue on a scenario I wouldn't expect, so please read through before downvoting or marking as duplicate.
I'm not restoring the database, just running single INSERT queries, so is not a matter of ordering.
The referenced row does exist on the table; me and my colleagues had it triple checked.
As one might expect, disabling the FK checks with SET foreign_key_checks = 0 does make the query work.
I've seen this happening because of different table charsets, but in this case, both use utf8mb4. Also both have collation set to utf8mb4_general_ci.
This is happening in a production environment, so dropping the tables and recreating them is something I would like to avoid.
Some additional information:
The FK constraint was created AFTER the original tables were already populated.
Here is the relevant portion of the current DDL:
CREATE TABLE `VehicleTickets` (
`id` varchar(50) NOT NULL,
`vehiclePlate` char(7) NOT NULL,
`organizationId` varchar(50) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'OPEN',
`description` text NULL DEFAULT NULL,
`ticketInfo` json DEFAULT NULL,
`externalId` varchar(100) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.externalId'))) VIRTUAL,
`value` decimal(10,2) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.value'))) VIRTUAL,
`issuedAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.issuedAt'))) VIRTUAL NOT NULL,
`expiresAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.expiresAt'))) VIRTUAL NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `VehicleTickets_externalId_unq_idx` (`externalId`,`organizationId`),
KEY `VehicleTickets_vehiclePlate_idx` (`vehiclePlate`),
KEY `VehicleTickets_organizationId_idx` (`organizationId`),
KEY `VehicleTickets_issuedAt_idx` (`createdAt`),
KEY `VehicleTickets_expiresAt_idx` (`expiresAt`),
CONSTRAINT `VehicleTickets_Organizations_fk`
FOREIGN KEY (`organizationId`) REFERENCES `Organizations` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `Organizations` (
`id` varchar(50) NOT NULL,
`name` varchar(100) NOT NULL,
`taxPayerId` varchar(50) DEFAULT NULL,
`businessName` varchar(100) DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'TESTING',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`activatedAt` timestamp NULL DEFAULT NULL,
`assetConfiguration` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
When I run:
select * from VehicleTickets where organizationId not in (
select id from Organizations
);
I get an empty result set.
However, if I run a query like this:
insert into `VehicleTickets` (
`id`,
`createdAt`,
`organizationId`,
`ticketInfo`,
`vehiclePlate`
)
values (
'... application generated id',
'... current date ',
'cjlchoksi01r8nfks3f51kht8', -- DOES EXIST on Organizations
'{ ... some JSON payload }',
'... vehicle plate'
)
This produces the following error:
Cannot add or update a child row: a foreign key constraint fails
(VehicleTickets, CONSTRAINT VehicleTickets_Organizations_fk
FOREIGN KEY (organizationId) REFERENCES Organizations (id))
Additionally, it gives me:
"errno": 1452,
"sqlState": "23000",
I've read through several threads regarding this issue, but couldn't find a similar case.

Insert GENERATED ALWAYS as in SQL

I created a table like this:
CREATE TABLE `group` (
`g_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`owner_id` int(10) unsigned NOT NULL,
`g_name` varchar(45) NOT NULL,
`refer_code` varchar(45) GENERATED ALWAYS AS (concat(`g_name`)) VIRTUAL,
`created_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`row_hash` varchar(256) NOT NULL,
PRIMARY KEY (`g_id`),
UNIQUE KEY `g_hash_UNIQUE` (`row_hash`),
UNIQUE KEY `refer_UNIQUE` (`refer_code`),
KEY `owner_idx` (`owner_id`),
CONSTRAINT `owner_id` FOREIGN KEY (`owner_id`) REFERENCES `user` (`u_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The update statement gives me error:
INSERT INTO `server`.`group` (`owner_id`, `g_name`, `refer_code`, `created_on`, `row_hash`)
VALUES ('4', 'cool', null, '2018-02-13 10:34:11', '452345324')
Error Code: 3105. The value specified for generated column 'refer_code' in table 'group' is not allowed.
How to specify the refer_code while inserting?
Values of the generated column are computed from the expression in the column definition of your CREATE TABLE, so don't include it in INSERT or UPDATE statements:
INSERT INTO `server`.`group` (`owner_id`, `g_name`, `created_on`, `row_hash`)
VALUES ('4', 'cool', '2018-02-13 10:34:11', '452345324')

Can I add a Unique key on table creation in SQL?

I am trying to translate a collection of MySQL functions to SQL, and I'm having issues with a UNIQUE KEY issue:
-- -----------------------------------------------------
-- Table testform
-- -----------------------------------------------------
CREATE TABLE `testform` (
`FormId` INT(11) NOT NULL AUTO_INCREMENT,
`TTId` INT(11) NULL DEFAULT NULL,
`TestName` VARCHAR(100) NULL,
PRIMARY KEY (`FormId`),
UNIQUE KEY `TF_Composite` (`TTId`, `TestName`));
When I try and test this in SQLFiddle, it's giving me the error
Incorrect syntax near the keyword 'KEY'.
I have tried searching for this, but so far all I have come up with is "Unique Constraints". Is there a difference between a "Key" and a "Constraint" in SQL? And if so, how can I add this in the table creation statement?
Your syntax is all messed up. Please look at books on-line (MSDN).
https://msdn.microsoft.com/en-us/library/ms174979.aspx
The sample code below create a table in tempdb. This table automatically gets destroyed when the service is restarted.
-- Just a example, throw away after reboot
USE [tempdb]
GO
-- Create the table
CREATE TABLE DBO.TESTFORM
(
FORM_ID INT IDENTITY(1, 1) NOT NULL ,
TT_ID INT NULL,
TEST_NAME VARCHAR(100) NULL,
CONSTRAINT PK_FORM_ID PRIMARY KEY (FORM_ID),
CONSTRAINT UN_COMPOSIT UNIQUE (TT_ID, TEST_NAME)
);
-- Seventies Band
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (1, 'John');
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (2, 'Paul');
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (3, 'Mary');
GO
-- Show data
SELECT * FROM TEMPDB.DBO.TESTFORM
GO
The image below shows the data in this table.
Try This.
CREATE TABLE testform (
FormId INT(11) NOT NULL AUTO_INCREMENT,
TTId INT(11) NULL DEFAULT NULL,
TestName VARCHAR(100) NULL,
PRIMARY KEY (FormId),
CONSTRAINT TF_Composite UNIQUE (TTId,TestName));
More Details..
For Better Understanding about Primary and Unique you can refer below page.
Primary and Unique Key Creation
For MySQL Database
CREATE TABLE `phone` (
`id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`country` DECIMAL(5,0) UNSIGNED NOT NULL,
`area` DECIMAL(5,0) UNSIGNED NOT NULL,
`number` DECIMAL(8,0) UNSIGNED NOT NULL,
`extension` DECIMAL(5,0) UNSIGNED DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ix_phone` (`country`, `area`, `number`, `extension`),
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
For alter Table :
ALTER TABLEphone
ADD UNIQUE INDEXix_phone(country,area,number,extension);

Mysql how to add more than one value (in one box)

I am trying to add more than one value
INSERT INTO Requierments (item_ID, SName) VALUES (
05, 'Exotic Weapons''basic weapon');
is that possible? i have all ready tried | and & but i am not allowed to do that.
the idea is to demonstrate that item_ID requires more than one Sname.
and if no SName are needed, how do i code that, in the alter table it shows me that they are by default '0' for item_ID and '' for Sname, but when i try:
INSERT INTO Requierments (item_ID, SName) VALUES (
02, '');
or
INSERT INTO Requierments (item_ID, SName) VALUES (
02, );
error occurs. item_ID and SName are the primary key and foreign key to two different tables
CREATE TABLE `requierments` (
`item_ID` int(11) NOT NULL DEFAULT '0',
`SName` varchar(30) NOT NULL DEFAULT '',
PRIMARY KEY (`item_ID`,`SName`),
KEY `SName` (`SName`),
CONSTRAINT `requierments_ibfk_1` FOREIGN KEY (`item_ID`) REFERENCES `item` (`ID`),
CONSTRAINT `requierments_ibfk_2` FOREIGN KEY (`SName`) REFERENCES `talents` (`SkillName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `talents` (
`SkillName` varchar(40) NOT NULL DEFAULT '',
`Bonus` varchar(30) DEFAULT NULL,
`Description` varchar(90) DEFAULT NULL,
`R_Str` int(11) DEFAULT NULL,
`R_WS` int(11) DEFAULT NULL,
`R_BS` int(11) DEFAULT NULL,
`R_Fel` int(11) DEFAULT NULL,
`R_Per` int(11) DEFAULT NULL,
`R_Int` int(11) DEFAULT NULL,
`R_Agi` int(11) DEFAULT NULL,
`R_WP` int(11) DEFAULT NULL,
`Talent_requiret` varchar(40) DEFAULT NULL,
PRIMARY KEY (`SkillName`),
KEY `Talent_requiret` (`Talent_requiret`),
CONSTRAINT `talents_ibfk_1` FOREIGN KEY (`Talent_requiret`) REFERENCES `talents` (`SkillName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `item` (
`ID` int(11) NOT NULL DEFAULT '0',
`Name_` varchar(30) DEFAULT NULL,
`Weight` int(11) DEFAULT NULL,
`Value_` int(11) DEFAULT NULL,
`Availability` varchar(30) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here are the 3 tables where i want to store in the requirement table what item_ID requires to be used under SName, since one item can be required to have more than one SName or none, it get confused on what to do.
The 'Exotic Weapons''basic weapon' syntax is interpreted as 'Exotic Weapons'basic weapon' (see the manual page on String Literals). You can store both, if you separate them with a special character like a comma or something ('Exotic Weapons,basic weapon'), but this is a bad idea, for the reasons that follow.
Anytime you are tempted to store multiple values in one column, you should have a new table to store each value and link it to the item_ID in question. This is called "normalization" - it makes your database more stable, your application code simpler, and everything just more likely to work as you move forward and modify things. Search for "database normalization" and read about how to do the kind of thing you are trying to do.
EDIT: It's still a little hard to tell what you're trying to do, but it looks like you just want to store multiple tuples in items. Example:
INSERT INTO Requierments (item_ID, SName) VALUES
(5, 'Exotic Weapons'),
(5, 'basic weapon');
Note that it should be 5, not 05. That's why INSERT INTO Requierments (item_ID, SName) VALUES ( 02, ''); fails. Also, you can't just omit a value and have blank space, like in your other example: INSERT INTO Requierments (item_ID, SName) VALUES ( 02, );
Honestly, it's very hard to tell what you're even trying to do here, and there seems to be some confusion about the basics of table structure and SQL syntax. For example, this statement is very confusing and unclear: "since one item can be required to have more than one SName or none, it get confused on what to do." If you can provide some more clarity about how you want the tables to relate to each other and where you are stuck, you will get more help from the SO community.

on duplicate key update fails with error "Cannot add or update a child row"

I have a table with a compound primary key "name" and "id". The fields are actually "name","id","phone","amount","units","alias". I have the query
insert into MyTable (name,id,phone,amount) select "henry" as name, id,phone,amount from anotherTable
on duplicate key update phone=values(phone),amount=values(amount).
MySQL spits the following error:
Cannot add or update a child row: a foreign key constraint fails.
BTW, "id" is a foreign key.
Any help?
as requested below, the schema for other table is
CREATE TABLE `otherTable` (
`otherId` int(11) NOT NULL AUTO_INCREMENT,
`DOBId` int(11) NOT NULL,
`bankAccount` int(11) DEFAULT NULL,
`partialAmount` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`notes` varchar(299) DEFAULT NULL,
`latitude` decimal(8,5) DEFAULT NULL,
`longitude` decimal(8,5) DEFAULT NULL,
PRIMARY KEY (`otherId `),
KEY `DOBId ` (`DOBId `),
KEY `bankAccount ` (`bankAccount `),
KEY `id ` (`id `)
) ENGINE=InnoDB AUTO_INCREMENT=3305 DEFAULT CHARSET=utf8;
for myTable
CREATE TABLE `myTable` (
`name` int(11) NOT NULL,
`id` int(11) NOT NULL,
`appleNumber` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`windowsNumber` int(11) DEFAULT NULL,
`phone` int(11) DEFAULT NULL,
`pens` int(11) DEFAULT NULL,
`pencils` int(11) DEFAULT NULL,
PRIMARY KEY (`name`,`id`),
KEY `id` (`id`),
CONSTRAINT `myTable_ibfk_1` FOREIGN KEY (`id`) REFERENCES `yet_another` (`id`)
The problem appears to be that the FK constraint you have on myTable is referencing the ids of yet_another, so when you are inserting ids from anotherTable you are breaking this FK constraint. Chances are there are ids in anotherTable that do not exist in yet_another table.
Understand this is a shot in the dark, based on the abstracted schema you posted. If you want a more solid answer, I'd have to see the actual schema.
The on duplicate key applies to the primary key. I take it you're using innodb. This is failing on a foreign key constraint. Which values of you table MyTable are foreign keys? Please post the create statement for the table that shows all keys and constraints for more detailed help.
Just a guess, but for grins I'm betting it's a column that's not in the insert that is a foreign key not allowing a null value.