foreign key constraint error in java - mysql

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

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 create table, constraint, foreign key

I am following along with a UDEMY course about SQL. The instructor is working in postgresql. I am working in MySQL workbench. Our corporate development is in MySQL 5.6 on the AWS platform. So I want to learn in MySQL.
There is a lecture about "creating tables" and using constraint and foreign key commands to link the primary keys in two different tables. This is something I want to do with my data, so the challenge is relevant. The instructor's code does not compile for me. I get "error code 1215. Cannot add foreign key constraint".
I have read here that the variables must have the exact same definition. So I changed the instructor's tables from "serial" to int. I am still getting the error. I have tried simplifying the code. I'm still not getting anywhere. Can anybody help me understand why it is not executing?
create table if not exists accounts(
user_id INT auto_increment not null,
username varchar(50) unique not null,
password varchar(50) not null,
email varchar(350) unique not null,
created_on timestamp not null,
last_login timestamp,
primary key (user_id)
);
create table if not exists role(
role_id INT auto_increment not null,
role_name varchar(250) unique not null,
PRIMARY KEY (role_id)
);
create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),
constraint accounts_role_role_id_fkey foreign key (role_id)
references role(role_id) match simple
on update no action
on delete no action,
constraint accounts_role_user_id_fkey foreign key (user_id)
references account (user_id) MATCH SIMPLE
on update no action
on delete no action
);
good grief.
Thanks Caius, i was implementing your suggestion and I found the answer to my problem.
i realized that my table is named "accounts" and i was creating a constraint on "account" ...
create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),
constraint accounts_role_role_id_fkey foreign key (role_id)
references role(role_id) match simple
on update no action
on delete no action,
constraint accounts_role_user_id_fkey foreign key (user_id)
references accounts(user_id) MATCH SIMPLE
on update no action
on delete no action
);

mariadb foriegn key insert error

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/

MySQL error 1215 Cannot add Foreign key constraint - FK in different tables

im new on mysql workbench, and i tried so many things to put my script working but i simply cant... Ive got these tables:
CREATE TABLE Utilizador (email varchar(40) not null, nome varchar(50)
not null, dataNascimento date, profissao varchar(50) not null,
reputacao double(3,2) unsigned not null, constraint pk_Utilizador
primary key(email))
This is the first table created!
CREATE TABLE POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, coordenadaX int, coordenadaY int,
descricaoPOI varchar(200), constraint pk_POI primary key(email,
designacaoPOI), constraint fk_POI foreign key(email) references
Utilizador(email) on delete cascade)
This is the second table created!
CREATE TABLE Utilizador_POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, constraint pk_Utilizador_POI primary key(email,
designacaoPOI), constraint fk1_Utilizador_POI foreign key(email)
references Utilizador(email) on delete cascade, constraint
fk2_Utilizador_POI foreign key(designacaoPOI) references
POI(designacaoPOI) on delete cascade)
This table gives me the error: Error Code: 1215. Cannot add foreign key constraint
I did some tests and im almost sure that the problem is in the foreign key "designacaoPOI". The other FK ("email") dont give me any error, so maybe the problem is in the Table POI?
Thanks in advanced!
The problem here is twofold:
1/ Use IDs for PRIMARY KEYs
You should be using IDs for primary keys rather than VARCHARs or anything that has any real-world "business meaning". If you want the email to be unique within the Utilizador table, the combination of email and designacaoPOI to be unique in the POI table, and the same combination (email and designacaoPOI) to be unique in Utilizador_POI, you should be using UNIQUE KEY constraints rather than PRIMARY KEY constraints.
2/ You cannot DELETE CASCADE on a FOREIGN KEY that doesn't reference the PRIMARY KEY
In your third table, Utilizador_POI, you have two FOREIGN KEYs references POI. Unfortunately, the PRIMARY KEY on POI is a composite key, so MySQL has no idea how to handle a DELETE CASCADE, as there is not a one-to-one relationship between the FOREIGN KEY in Utilizador_POI and the PRIMARY KEY of POI.
If you change your tables to all have a PRIMARY KEY of ID, as follows:
CREATE TABLE blah (
id INT(9) AUTO_INCREMENT NOT NULL
....
PRIMARY KEY (id)
);
Then you can reference each table by ID, and both your FOREIGN KEYs and DELETE CASCADEs will work.
I think the problem is that Utilizador_POI.email references POI.email, which itself references Utilizador.email. MySQL is probably upset at the double-linking.
Also, since there seems to be a many-to-many relationship between Utilizador and POI, I think the structure of Utilizador_POI isn't what you really want. Instead, Utilizador_POI should reference a primary key from Utilizador, and a matching primary key from POI.
The problem is in your second table. Your primary key is (email,designacaoPOI), when you try to reference that in your table it gives you error because of this:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
For it to work, either change the order of your second tale PRIMARY KEY :
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email), -- changed the order
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
or add an index for designacaoPOI:
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email),
KEY key_designacaoPOI(designacaoPOI), -- added index for that column
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
Either of these solutions will let you create your third table without errors.

Mysql Cannot add foreign key constraint for my tables

Hey guys getting an Error code 1215, SQL state HY000: Cannot add foreign key constraint for my PERSON_GROUP table and IMAGES table.. Don't know why, is there something wrong with my referencing? I've tried rewriting it but its just not working...
Updated code im now just getting an error for FOREIGN KEY (ID) REFERENCES INSTRUMENT(ID)
You can only create foreign keys that reference either the primary key or a unique key. Since ID is the primary key of PERSON change your foreign keys to point to ID instead of email. You could also make email a unique column, which is probably a good idea to make sure no one reuse the same email address, but it is still less storage to make foreign keys on an integer then a string.
I had this problem. The problem was database engine. Until i added the ENGINE=MyISAM DEFAULT CHARSET=latin1 before it worked. I guess my default was innoDB or something else.
CREATE TABLE LECTURE_NOTE (
ID bigint(20) NOT NULL,
NOTE VARCHAR(1000) NOT NULL,
NOTE_DATE TIMESTAMP NULL DEFAULT NULL,
LECTURE_ID bigint(20) NOT NULL,
PUBLISHER_ID bigint(20) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_lecture_id FOREIGN KEY (LECTURE_ID) REFERENCES
COURSE_LECTURE (ID),
CONSTRAINT fk_publisher_id FOREIGN KEY (PUBLISHER_ID) REFERENCES
PUBLISHER (ID)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;