mariadb foriegn key insert error - mysql

So, I was using mysql server on Centos 6 and it was alright then, I shifted my code to Centos 7 server.
I had a constraint in an table where I used to insert null values by default in MySQL Server. I guess thats not happenning in MariaDB.
I get the following error when inserting data.
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (dbName.tableName, CONSTRAINT constraintName FOREIGN KEY (columnName) REFERENCES externalTableName (externalTableColumnName))
Any help would be appreciated.
Thanks
UPDATE 1 :
Table with the key to be referenced :
CREATE TABLE `users` (
`uid` int(25) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`uid`)
);
CREATE TABLE `abc_xyz` (
`isUser` int(25) DEFAULT NULL,
`last_modified_user` int(25) DEFAULT NULL,
KEY `abc_xyz_is_user` (`isUser`),
KEY `abc_xyz_last_modified_user` (`last_modified_user`),
CONSTRAINT `abc_xyz_is_user` FOREIGN KEY (`isUser`) REFERENCES `users` (`uid`),
CONSTRAINT `abc_xyz_last_modified_user`
FOREIGN KEY (`last_modified_user`) REFERENCES `users` (`uid`)
);

If the columnName is NULLable then you are not inserting a NULL value. I really doubt that inserting NULL in a NULLable column can create a foreign key failure. Check the query being called (if you use ORM, etc).

The issue is that your referring column can contain a NULL value while the referred column cannot (it's a PRIMARY KEY). You can't enter a default null value in the abc_xyz.last_modified_user column and maintain a valid foreign key to the users.uid that cannot accept null.
A PRIMARY KEY Constraint is either a < Table Constraint> or a and defines a rule that constrains a unique key to non-duplicate, non-null values only. The required syntax for a PRIMARY KEY Constraint is:
https://mariadb.com/kb/en/sql-99/constraint_type-primary-key-constraint/

Related

Remove primary key(s) - Foreign key constraint is incorrectly formed

I cannot seem to be able to delete primary keys in a table.
All references (FKs) have been removed but it still doesn't let me delete it.
What I'm trying to do is: delete old primary keys to add a new one - but keep the old columns and data (just remove the PK attribute).
What is wrong ?
Table:
CREATE TABLE `employee` (
`User` int(10) unsigned NOT NULL,
`Company` int(10) unsigned NOT NULL,
--unrelated boolean fields
PRIMARY KEY (`User`,`Company`),
KEY `FK_Employee_Company_idx` (`Company`),
CONSTRAINT `FK_Employee_Company` FOREIGN KEY (`Company`) REFERENCES `company` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_Employee_User` FOREIGN KEY (`User`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Trying to delete:
alter table Employee
drop primary key;
Issue:
Error 1025: Error on rename of '.\DB_NAME#sql-3640_4' to '.\DB_NAME\employee' (errno: 150 "Foreign key constraint is incorrectly formed") SQL Statement: ALTER TABLE DB_NAME.employee DROP PRIMARY KEY
Nothing references this table anymore. I also checked via statements which select from information_schema.key_column_usage but yields no results.
Wasted the last hours on Google but can't seem to figure it out.
And if that would work, adding a new column:
alter table Employee
add column ID int unsigned not null auto_increment primary key;
The index is still needed for the existing FK constraints.
Adding the following index (first) should satisfy that requirement:
CREATE INDEX xxx ON employee (User, Company);
Test case

MySQL: Can't create table

I tried to create a table in MySQL using the CREATE TABLE statement below:
CREATE TABLE `visit` (
`visit_id` int(11) NOT NULL,
`site_id` int(11) DEFAULT NULL,
PRIMARY KEY (`visit_id`),
CONSTRAINT `FK_visit_site` FOREIGN KEY (`site_id`) REFERENCES `site` (`site_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I received this error:
ERROR 1005 (HY000): Can't create table 'fooschema.visit' (errno: 121)
I used SHOW ENGINE INNODB STATUS command. This is the error message:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
140222 7:03:17 Error in foreign key constraint creation for table `fooschema`.`visit`.
A foreign key constraint of name `fooschema/FK_visit_site`
already exists. (Note that internally InnoDB adds 'databasename/'
in front of the user-defined constraint name).
Note that InnoDB's FOREIGN KEY system tables store
constraint names as case-insensitive, with the
MySQL standard latin1_swedish_ci collation. If you
create tables or databases whose names differ only in
the character case, then collisions in constraint
names can occur. Workaround: name your constraints
explicitly with unique names.
Then, I used the query below to list all available constraints:
select *
from information_schema.table_constraints
where constraint_schema = 'fooschema'
I didn't see any constraint with name 'FK_visit_site' in the result.
The FK_visit_site constraint was a foreign key constraint of table visit. I dropped the visit table and attempted to recreate it.
Is there a way I can drop this foreign key constraint even when the table it was associated to doesn't exist?
your foreign key already exist , so either drop existed foreign key or rename your second key.
ALTER TABLE `site` DROP FOREIGN KEY `FK_visit_site`;
or rename to other new one.
CREATE TABLE `visit` (
`visit_id` int(11) NOT NULL PRIMARY KEY,
`site_id` int(11) NOT NULL,
CONSTRAINT `FK_visit_site` FOREIGN KEY (`site_id`) REFERENCES `site` (`site_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Added PRIMARY KEY to the visit_id line.
Note:
make sure that site_id in the site table have exact same datatype of site_id in visit table.
like that
`site_id` int(11) DEFAULT NULL --//in the `site` table
The two keys you're coupling must have the exact same datatype ( INT NOT NULL), even signedness
AFAIK, you will get this error when you're trying to add a constraint with a name that's already used somewhere else. Means, in your case FK FK_visit_site had already been used before.
If the table you're trying to create includes a foreign key constraint, and you've provided your own name for that constraint, remember that it must be unique within the database.
You can run the below query to find out the same
SELECT
constraint_name,
table_name
FROM
information_schema.table_constraints
WHERE
constraint_type = 'FOREIGN KEY'
AND table_schema = DATABASE()
ORDER BY
constraint_name;
Taken from the post here
http://www.thenoyes.com/littlenoise/?p=81
Try using a different name for your FK like
CREATE TABLE `visit` (
`visit_id` int(11) NOT NULL,
`site_id` int(11) DEFAULT NULL,
PRIMARY KEY (`visit_id`),
CONSTRAINT `FK_visit_site_New` FOREIGN KEY (`site_id`)
REFERENCES `site` (`site_id`),
)

foreign key constraint error in java

my java cannot execute this code, and gives me error like "cannot add key constraint"
Please Help me
st.executeUpdate("CREATE TABLE `e166713`.`shopping` ( "
`idShopping` INT NOT NULL,
`idUser` VARCHAR(45) NULL,
PRIMARY KEY (`idShopping`),
INDEX `user_idx` (`idUser` ASC),
CONSTRAINT `user`
FOREIGN KEY (`idUser`)
REFERENCES `e166713`.`user` (`uID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)");
This could mean two things:
Either user table is not created yet
or
uID in user table is not of the same data type as idUser :
varchar(45).
The columns need to be the exact same data type in both tables.
sqlfiddle demo

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I have created two tables in MySQL 5.6.11 as shown below by means of MySQL Workbench 5.2.47.
The country table:
delimiter $$
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INC
REMENT=2 DEFAULT CHARSET=utf8$$
The state_table:
delimiter $$
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`id`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT=''$$
There is one row in the country table with the id 1. It allows only one (child) row to be inserted into its child table state_table. If more rows are attempted, then the following error occurs.
ERROR 1452: Cannot add or update a child row: a foreign key constraint
fails (social_networking.state_table, CONSTRAINT country_fk
FOREIGN KEY (id) REFERENCES country (id) ON DELETE CASCADE ON
UPDATE CASCADE)
SQL Statement:
INSERT INTO `social_networking`.`state_table` (`id`, `state_name`, `country_id`) VALUES ('2', 'xxx', '1')
Actually, I'm trying to map these tables using an ORM (JPA) where I always see only OneToOne relationship.
What am I missing?
Well, I find the answer, the solution, my english is not very well but I think can explain you. I get this error after try to create a trigger, My database was created in phpmyadmin, and this error was make me crazy, the problem was that I before create the trigger, I load a lot of data in my tables, and in my child table was some data that have no match in my parent table, ej: my child table "chat" have a "id_jugador=1" and in my parent table there wasn't that "id_jugador", that was my mistake, I hope help you, Argentina Rulz ;)
I think you have a typo in your foreign key constraint, country_id should probaby be the foreign key to country. When id is the foreign key, you can only insert one row since it just happens to get id=1 which is the same id as the row in country;
CONSTRAINT `country_fk` FOREIGN KEY (`id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
should probably be
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
An SQLfiddle to test with.
I had the same problem and it was not wrong relationships name.
I had problem with different records, ie, tried registering a record that did not exist in another table so generated this error.
Check if the record exists in another table to insert their correct relationship, otherwise, this error appears.
Hope this help you.
example:
table1(
id1 INT PRIMARY KEY,
name1 VARCHAR(50)
)
table2(
id2,<--- want to add FOREIGN KEY to this field
name2 VARCHAR(50)
)
Before adding constraint foreign key you must have the right value between id1 and id2, so you should update that id field with the value that map each other.
Possible Solution
if you have live data, then check all column values.
i.e. if you have 'x'->table as primary one having 'a'->column and 'y'->table as secondary with 'b'->column, then all values in 'b'->column must exist in 'a'->column if any value that exists in 'b'->column and not exist in 'a'->column then it will give as such error..
Hope this help.. for newbie..

MySQL Composite Foreign Key Insert Failing

I have 2 tables with a composite foreign key between the 2. When I try to insert a row into the child table, I get a restraint failure, even though the values exist in the parent table.
Here's a overview of the parent table:
CREATE TABLE `residual_reports` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`processor` enum('1','2','3') NOT NULL,
`posting_date` date NOT NULL DEFAULT '0000-00-00',
`approved_on` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `posting_date_2` (`processor`,`posting_date`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
The child table has the foreign key to the processor and posting date columns:
CREATE TABLE `residual_data` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`mid` varchar(29) DEFAULT NULL,
`processor` enum('1','2','3') NOT NULL,
`posting_date` date NOT NULL,
......
PRIMARY KEY (`id`),
KEY `residual_data_ibfk_1` (`processor`,`posting_date`),
CONSTRAINT `residual_data_ibfk_1` FOREIGN KEY (`processor`, `posting_date`) REFERENCES `residual_reports` (`processor`, `posting_date`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I inserted a row into the residual_reports table with processor = 1, and posting_date = 2010-03-10.
When I try to insert into the residual_data table with processor = 1, and posting_date = 2010-03-10.
INSERT INTO `residual_data`(processor,posting_date) VALUES ('1','2010-03-10');
I get an:
[Err] 1452 - Cannot add or update a child row: a foreign key constraint fails (residual_data, CONSTRAINT residual_data_ibfk_1 FOREIGN KEY (processor, posting_date) REFERENCES residual_reports (processor, posting_date) ON UPDATE CASCADE)
Verified that the values definitely exist in the parent table, but still get foreign key restraint errors. Is there something I'm missing with a composite foreign key?
I would suspect the ENUM's, did you do something with them afterwards? Did you change values or so?
Your code works for me as-is. Is it possible that changes to residual_reports have not been committed yet?
What Mysql version do you use? It seems that they have similar problems before with enum values
http://bugs.mysql.com/bug.php?id=24985