Having trouble adding a foreign key to my table.
CREATE TABLE event (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
issued DATETIME NOT NULL,
user VARCHAR(255) NOT NULL,
subject VARCHAR(255) NOT NULL,
attending BIGINT(255) NOT NULL,
attendees VARCHAR(255) NOT NULL,
organisers VARCHAR(255) NOT NULL,
place BIGINT(20) NOT NULL,
started DATETIME NOT NULL,
stopped DATETIME NOT NULL,
content LONGTEXT NOT NULL,
broadcasting TINYINT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (place)
REFERENCES place (id),
FOREIGN KEY (user)
REFERENCES user (username)
)
The foreign key for place is executing fine but once I try adding user as a foreign key I keep getting the same error:
Error Code: 1005. Can't create table 'iservices.event' (errno: 150)
Can anyone help?
Picture of user table:
User table
Picture of place table:
Place table
Is there anyway of expanding the errors in MySQL Workbench?
a foreign key has to be unique, so make username unique (which is probably not the best idea) or choose something different like the user id.
My advice: add a primary auto-increment key to the user table and use it as the foreign-key.
Referenced column must be unique. It's OK in your case.
Columns in child and parent table must be of the same type. In your case they are different.
Could you please make sure user and place tables exist and have corresponding columns set as primary key? The below snipper works fine:
CREATE TABLE user(username VARCHAR(255) PRIMARY KEY);
CREATE TABLE place(id BIGINT(20) PRIMARY KEY);
CREATE TABLE event (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
issued DATETIME NOT NULL,
user VARCHAR(255) NOT NULL,
subject VARCHAR(255) NOT NULL,
attending BIGINT(255) NOT NULL,
attendees VARCHAR(255) NOT NULL,
organisers VARCHAR(255) NOT NULL,
place BIGINT(20) NOT NULL,
started DATETIME NOT NULL,
stopped DATETIME NOT NULL,
content LONGTEXT NOT NULL,
broadcasting TINYINT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (place)
REFERENCES place (id),
FOREIGN KEY (user)
REFERENCES user (username)
)
Here's SQL Fiddle.
I had encountered a similar error.
This can occur when you are trying to add a non-primary key from the primary table as the foreign key in the secondary table.
To avoid this, the foreign key in the secondary table has to be the primary key in the primary table.
Related
So I'm working on a project in school in which we use MySQL to make a database and complete various tasks about school subjects and exam boards. One of my questions was to:
"Create and populate a third table called entries, again using query scripts. This table should contain foreign keys to allow sensible links to be made with the other two tables, together with the dates of each exam."
When carrying out this task I tried this code out
CREATE TABLE IF NOT EXISTS entries(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(20) NOT NULL,
level_of_entry VARCHAR(10) NOT NULL,
exam_board VARCHAR(10) NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (date_of_exam),
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id)
);
And that worked fine, but when I tried this:
CREATE TABLE IF NOT EXISTS entries(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(20) NOT NULL,
level_of_entry VARCHAR(10) NOT NULL,
exam_board VARCHAR(10) NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (date_of_exam),
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id),
FOREIGN KEY (subject_name) REFERENCES subjects(subject_name)
);
It threw up and error message stating:
"ERROR 1215 (HY000): Cannot add foreign key constraint"
Any clues on how to add multiple foreign key statements without it causing an error. Also I did try using the ALTER TABLE function and that didn't work,
Many thanks
Andrew.
i am trying to delete the table appusers, with the following command:
drop table appusers;
and i get the following error:
Cannot delete or update a parent row: a foreign key constraint fails
this is the scheme for my tables.
CREATE TABLE appUsers (
uid INT PRIMARY KEY AUTO_INCREMENT,
fullName VARCHAR(80) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
Gender VARCHAR(7) NOT NULL, /*["Male", "Female"]*/
Country VARCHAR(150) NOT NULL,
Bdate date NOT NULL,
Status VARCHAR(25) NOT NULL, /*["Single", "In Relationship", "Merried", "Divorced", "Widow"]*/ /*check married!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
Religion VARCHAR(25) NOT NULL, /*["Jewish", "Christian", "Muslim", "Atheist", "Other"]*/
ReligionStrength INT(1) NOT NULL, /*0-5*/
PoliticalView VARCHAR(25) NOT NULL, /*["Left Wing","Center","Right Wing"]*/
Occupation VARCHAR(25) NOT NULL, /*["Unemployed","White Collar","Blue Collar","Student", "Independent"]*/
Volunteering VARCHAR(25) NOT NULL, /*["Yes", "No"]*/
Donating VARCHAR(25) NOT NULL, /*["Yes", "No"]*/
Economy VARCHAR(25) NOT NULL, /*["Poor","Middle Class","Rich"]*/
EducationalYears INT(2) NOT NULL
);
and I have the following table
CREATE TABLE Accelerometer(
id INT PRIMARY KEY AUTO_INCREMENT,
uid INT NOT NULL,
sampleTime timestamp(2) NOT NULL,
data VARCHAR(100) NOT NULL,
FOREIGN KEY (uid) REFERENCES appUsers(uid) ON DELETE CASCADE
);
as far as I know, if I delete the table appusers, the Accelerometer table should be deleted too,
what i am missing here?
ON DELETE CASCADEonly apply to data, not metadata.
=>
Alter TABLE Accelerometer drop FOREIGN KEY (uid);
Then only
drop table appusers;
I realise this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
The following might work nicely for you:
ALTER TABLE 'Accelerometer'
DROP FOREIGN KEY 'uid_fk';
ALTER TABLE 'Accelerometer'
ADD CONSTRAINT 'uid_fk' FOREIGN KEY ('uid') REFERENCES 'appUsers' ('uid') ON
UPDATE CASCADE ON DELETE SET NULL;`
Personally I would recommend using both ON UPDATE CASCADE as well as ON DELETE SET NULL to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.
I have created this table
CREATE TABLE `Overview` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ops` varchar(11) NOT NULL,
`date` date NOT NULL,
`title` text,
`beneficiary_Institution` varchar(100) DEFAULT NULL,
`description` longtext,
`public_Expenditure_Budget` decimal(14,2) DEFAULT NULL,
`payments` decimal(14,2) DEFAULT NULL,
`completition_percent` int(11) DEFAULT NULL,
`start` varchar(11) DEFAULT NULL,
`finish` varchar(11) DEFAULT NULL,
`sub_projects` int(11) DEFAULT NULL,
`public_aid` decimal(14,2) DEFAULT NULL,
`operational_programme_number` int(11) DEFAULT NULL,
`operational_programme` varchar(100) DEFAULT NULL,
`title_ops` text,
`map_coordinates` varchar(15000) DEFAULT NULL,
PRIMARY KEY (`id`,`ops`,`date`)
)ENGINE=InnoDB;
and i try to create a table that has a foreign key with that
CREATE TABLE `Proposal_Body` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`ops` VARCHAR(11) NULL,
`title` VARCHAR(100) NULL,
`representative` VARCHAR(45) NULL,
`address` VARCHAR(45) NULL,
`email` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
INDEX `fk_Proposal_Body_1_idx` (`ops` ASC),
CONSTRAINT `fk_Proposal_Body_1`
FOREIGN KEY (`ops`)
REFERENCES `espanew`.`Overview` (`ops`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)ENGINE=InnoDB;
This and any other attempt i tried gives me this error
ERROR 1005 (HY000): Can't create table
'Espa_Projects_Eng.Proposal_Body' (errno: 150)
I know that this is a foreign key problem, but i cant see the reason. This code is a comming from the mysql client, where i did the creation using the ui, didnt type the commands by hand, so it should work.
Thanks a lot
Reading from the documentation:
If you re-create a table that was dropped, it must have a definition
that conforms to the foreign key constraints referencing it. It must
have the correct column names and types, and it must have indexes on
the referenced keys, as stated earlier. If these are not satisfied,
MySQL returns Error 1005 and refers to Error 150 in the error message,
which means that a foreign key constraint was not correctly formed.
Similarly, if an ALTER TABLE fails due to Error 150, this means that a
foreign key definition would be incorrectly formed for the altered
table.
As you can see your first table has this primary key:
PRIMARY KEY (`id`,`ops`,`date`)
but in the second table the foreign key is:
FOREIGN KEY (`ops`)
You have to correct this to make it work.
Your Primary key is a composite key
PRIMARY KEY (id,ops,date)
And your foreign key is consist of only single column i.e.
FOREIGN KEY (ops)
Foreign keys have to match the primary/unique key they reference column for column. To remove this error either you need to add id and date to the Proposal_Body table or your first table Overview primary key is wrong and should just be (id).
While I am creating schema "Cannot add foreign key constraint" error I am getting.
Query is :
CREATE database sample;
USE sample;
CREATE TABLE sys_admin_user_t (
sys_admin_id MEDIUMINT NOT NULL,
admin_name VARCHAR(255) NOT NULL,
admin_password VARCHAR(255) NOT NULL,
PRIMARY KEY (sys_admin_id)
);
CREATE TABLE sys_user_roles_t (
role_id MEDIUMINT NOT NULL,
privilege_id MEDIUMINT NOT NULL,
role_name VARCHAR(255) NOT NULL,
role_description VARCHAR(255) NOT NULL,
created_by MEDIUMINT NOT NULL,
created_date DATE NOT NULL,
modified_by MEDIUMINT NOT NULL,
FOREIGN KEY (privilege_id) REFERENCES privileges_t (privilege_id),
FOREIGN KEY (created_by) REFERENCES sys_admin_user_t(sys_admin_id),
FOREIGN KEY (modified_by) REFERENCES sys_admin_user_t(sys_admin_id),
PRIMARY KEY (role_id)
);
Kindly some one help me to resolve this.
This can occur in the following cases:
You do not create the table privileges_t
In your table privileges_t does not exists primary key by field privilege_id
The field privilege_id from table sys_user_roles_t are not exactly the same data type as in table privileges_t
You are not using InnoDB as the engine on all tables
And to find the specific error run this:
SHOW ENGINE INNODB STATUS\G
I would like to ask something that troubles me many many days...
Here is what I mean:
I create these two tables:
CREATE TABLE IF NOT EXISTS journal (
issn varchar(20) NOT NULL,
j_title varchar(100) NOT NULL,
j_publisher varchar(30) NOT NULL,
PRIMARY KEY (issn)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS volume (
volume_no int(11) NOT NULL,
issn varchar(20) NOT NULL,
year int(11) NOT NULL,
PRIMARY KEY (issn,volume_no),
FOREIGN KEY (issn) REFERENCES journal(issn)
) ENGINE=InnoDB;
When I try to create this:
CREATE TABLE IF NOT EXISTS issue (
issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issue_no,issn,volume_no),
FOREIGN KEY (issn) REFERENCES journal(issn),
FOREIGN KEY (volume_no) REFERENCES volume(volume_no)
) ENGINE=InnoDB;
it throws an error (errno 150)
The error is in the foreign key volume_no.
Without FOREIGN KEY (volume_no) REFERENCES volume(volume_no)
the table is created without a problem.... I can't explain what's going on... I have seen it many times again and again but nothing!! Does anybody know what's going on?
Thanks in advance!!
I could see that the foreign key doesnt include issn but which is actually included in primary key for volumn table.
CREATE TABLE IF NOT EXISTS issue ( issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issue_no,issn,volume_no),
FOREIGN KEY (issn,volume_no) REFERENCES volume(issn,volume_no) ) ENGINE=InnoDB;
Look at the below sql fiddle.
http://sqlfiddle.com/#!2/55a63
maybe volume_no needs to be UNSIGNED
FOREIGN keys must reference a PRIMARY or a UNIQUE key in the parent table.
You need only one Foreign Key at table issue, not two. And it should reference the Primary Key of volume:
CREATE TABLE IF NOT EXISTS issue (
issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issn, volume_no, issue_no),
FOREIGN KEY (issn, volume_no)
REFERENCES volume(issn, volume_no)
) ENGINE=InnoDB;
If the PK of the parent table is more than one field, the order of the fields in the FK must be the same as the order in the PK.
issue: FOREIGN KEY (issn, volume_no) REFERENCES volume(issn, volume_no)
These conditions must be satisfied to not get error 150:
The two tables must be ENGINE=InnoDB.
The two tables must have the same charset.
The PK column(s) in the parent table and the FK column(s) must be the same data type.
The PK column(s) in the parent table and the FK column(s), if they have a define collation type, must have the same collation type;
If there is data already in the foreign key table, the FK column value(s) must match values in the parent table PK columns.
source: MySQL Creating tables with Foreign Keys giving errno: 150
I had about the same issue with my database. It wasn't about the definition of the foreign key, actually it was the definition of the primary key field.
CREATE TABLE tblProcesses (
fldProcessesID SMALLINT(5) UNIQUE NOT NULL AUTO_INCREMENT ,
CREATE TABLE tblProcessesMessage (
fldProcesses TEXT NOT NULL,
fldProcessesID VARCHAR(15) NOT NULL DEFAULT ,
The primary key in tblProcesses (fldProcessesID) did not have the UNSIGNED keyword while the foreign key in tblProcessesMessage (fldProcessesID) had the UNSIGNED keyword. This keyword was causing the problem - inconsistent type of field. So i added the UNSIGNED keyword to fldProcessesID in tblPreocesses:
CREATE TABLE tblProcesses (
fldProcessesID SMALLINT(5) UNSIGNED UNIQUE NOT NULL AUTO_INCREMENT,
I hope that this will help you solve your problems.
Best regards,
Nicholas