I am currently attempting to learn mysql and I am on the section of referencing foreign keys but cannot seem to get it to accept it.
What am I missing? Hope you can help :)
mysql> create table states (
-> id tinyint(3) not null primary key auto_increment,
-> name varchar(255));
Query OK, 0 rows affected (0.02 sec)
mysql> create table customers (
-> id integer(10) not null auto_increment primary key,
-> name varchar(255) not null,
-> email varchar(255) not null,
-> states_id tinyint unsigned not null,
-> foreign key(states_id) references states(id) on update cascade);
ERROR 1215 (HY000): Cannot add foreign key constraint
Columns related through foreign keys need to have the same data type. The id is TINYTINT(3) but states_id is TINYTINT UNSIGNED.
Redefine your definition of states and try it again.
Related
can anyone help with this error , when i run my code it comes up with error 1005 can't create table my code looks like this can anyone point out the source of this error im using codio mysql if that helps
CREATE TABLE IF NOT EXISTS entries (
entries_id INT NOT NULL AUTO_INCREMENT,
students_id INT UNSIGNED NOT NULL,
Date_of_exam DATETIME NOT NULL,
subjects_id INT UNSIGNED NOT NULL,
PRIMARY KEY (entries_id),
FOREIGN KEY (students_id) REFERENCES students(students_id),
FOREIGN KEY (subjects_id) REFERENCES subjects(subjects_id));
this is the error
mysql> SOURCE task7
ERROR 1005 (HY000): Can't create table 'exams.entries' (errno: 150)
This error related to foreign keys. Check following items:
Name of tables and columns that exist on foreign keys are correct.
Type of foreign keys columns are same.
Data of foreign keys not conflict with them.
Note: You can disable check foreign key on query. Sure enable this option after query.
SET FOREIGN_KEY_CHECKS=0;
CREATE TABLE IF NOT EXISTS entries (
entries_id INT NOT NULL AUTO_INCREMENT,
students_id INT UNSIGNED NOT NULL,
Date_of_exam DATETIME NOT NULL,
subjects_id INT UNSIGNED NOT NULL,
PRIMARY KEY (entries_id),
FOREIGN KEY (students_id) REFERENCES students(students_id),
FOREIGN KEY (subjects_id) REFERENCES subjects(subjects_id)
);
SET FOREIGN_KEY_CHECKS=1;
The error itself is related with the foreign keys (as removing them creates the table with no errors).
Main possible causes:
One of the referenced tables doesn't exists
The field of the referenced tables doesn't exists
The data types of the referenced table doesn't match (I assume is this).
As i can see your primary key on your table is INT, assuming you use INT as your primary keys, students_id is INT UNSIGNED, possibly the cause of your error.
I am getting error when I create table with foreign key
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id,_user_email,_user_mobile));
_users table created successfully..there were no error..
But When I want to create employee table :
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_mobile VARCHAR(15) not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_mobile) references _users(_user_mobile));
Its showing error:
ERROR 1005 (HY000): Can't create table 'DB.employee' (errno: 150)
What am I doing wrong??
Hey In this case you just need to do one thing ,
you just need to add index to the reference column of the user table and then run the create table for employee
ALTER TABLE `_users` ADD INDEX (`_user_mobile`);
After running above query just run the below query :-
CREATE TABLE `employee`(
`_Id` INT(11) NOT NULL AUTO_INCREMENT,
`_user_mobile` VARCHAR(15) NOT NULL,
`_name` VARCHAR(15),
`_org` VARCHAR(10),
PRIMARY KEY (`_Id`),
FOREIGN KEY (`_user_mobile`) REFERENCES `_users`(`_user_mobile`) );
In this way you will get rid of the error 1005 of mysql which says that you need to have index on the reference column of parent table.
150 is a foreign key error:
C:\>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
Getting the exact error message is very tricky. You need to run this query:
show engine innodb status
... and search in the output:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
160627 14:09:32 Error in foreign key constraint of table test/employee:
foreign key (_user_mobile) references _users(_user_mobile)):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Once you know that, it'd be easy to add the missing index:
ALTER TABLE `_users`
ADD UNIQUE INDEX `_user_email` (`_user_email`);
But I wouldn't if I were you. It's weird to use mobile phone number as key. Instead, just simplify the primary key:
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id));
... and use in the linked table:
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_id int(20) unsigned not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_id) references _users(_id));
The problem is in the foreign key part. If you remove that, table will be created without a problem.
If you need to use that foreign key, you need to use InnoDB as the storage engine of MySQL. InnoDB allows a foreign key constraint to reference a non-unique key as can be seen in here.
I need assistance, my 'Key column' says it does not exist when it clearly does.
CREATE TABLE PUBLISHER (
LISHER_ID INT PRIMARYKEY,
LISHER_NAME VARCHAR(5NNULL,
LISHER_ADDRESS VARCHAR(NOT NULL,
LISHER_PHONE VARCHAR(5) NULL,
LISHER_EMAIL VARCHAR(4) NULL);
The column you name in the FOREIGN KEY clause has to exist in the table on which you're defining the constraint - in this case, it has to be a column in the table CONTRACT.
At a guess, I think you probably want
CREATE TABLE CONTRACT (
...
CONSTRAINT FK_CONTRACT_PUBLICATION FOREIGN KEY (PUBLICATION_PUB_ID)
REFERENCES PUBLICATION (PUB_ID));
You appear to have two mistakes, both from what appears to be copy/paste. In your CONTRACT table, you named the column PUBLICATION_PUB_ID, but in your index definition and your foreign key constraint you tried to reference it as just PUB_ID.
mysql> CREATE TABLE CONTRACT (
-> CON_NUMBER INT NOT NULL PRIMARY KEY,
-> CON_STARTDATE DATETIME NOT NULL,
-> CON_ENDDATE DATETIME NOT NULL,
-> PUBLICATION_PUB_ID INT NOT NULL,
-> INDEX PUBLICATION (PUBLICATION_PUB_ID),
-> CONSTRAINT FK_CONTRACT_PUBLICATION FOREIGN KEY (PUBLICATION_PUB_ID) REFERENCES PUBLICATION (PUB_ID)) ;
EDIT # 2:-
After following Spencer 7593's answer, i.e. creating the table without the foreign keys, and then adding them using the alter table statement, the table was created successfully and the foreign keys were added successfully.
But now I wonder why? Why does it work when we create the table and then add the foreign key constraints using alter table statement, and not when we do it all in the create table statement?
I am creating the following tables in my database. The first two were created successfully but the third one is giving this error.
I checked my database for the points in this answer which I could understand. Please tell me why I am getting this error.
CREATE TABLE a (
a_id INT(255) NOT NULL AUTO_INCREMENT,
name VARCHAR(5000),
code VARCHAR(5000),
PRIMARY KEY (a_id)
);
CREATE TABLE b (
b_id INT(255) NOT NULL AUTO_INCREMENT,
b_name VARCHAR(5000),
PRIMARY KEY (b_id)
);
CREATE TABLE c ( -- error code 1005 can t create c errno 150 mysql
a_id INT(255), -- fk
b_id INT(255), -- fk
PRIMARY KEY (a_id, b_id),
FOREIGN KEY (a_id)
REFERENCES a (a_id),
FOREIGN KEY (b_id)
REFERENCES b(b_id)
);
EDIT:-
I executed just these three statements separately (after changing the size of all INT types to 11 - thanks to the comment by Michael Berkowski), and to my surprise, it did create the tables, but gave this log (if I am using the right word):
3 4 01:03:49 CREATE TABLE a (
a_id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(5000),
code VARCHAR(5000),
PRIMARY KEY (a_id)
) 0 row(s) affected 0.156 sec
3 5 01:03:54 CREATE TABLE b (
b_id INT(11) NOT NULL AUTO_INCREMENT,
b_name VARCHAR(5000),
PRIMARY KEY (b_id)
) 0 row(s) affected 0.234 sec
3 6 01:03:58 CREATE TABLE c ( -- error code 1005 can t create c errno 150 mysql
a_id INT(11), -- fk
b_id INT(11), -- fk
PRIMARY KEY (a_id, b_id),
FOREIGN KEY (a_id)
REFERENCES a (a_id),
FOREIGN KEY (b_id)
REFERENCES b(b_id)
) 0 row(s) affected 0.203 sec
That is all the three tables are created, but an error is returned at the creation of the third table.
EDIT # 3:-
Output from SHOW CREATE TABLE a, and SHOW CREATE TABLE b:-
CREATE TABLE `a` (
`a_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(5000) DEFAULT NULL,
`code` varchar(5000) DEFAULT NULL,
PRIMARY KEY (`a_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `b` (
`b_id` int(11) NOT NULL AUTO_INCREMENT,
`b_name` varchar(5000) DEFAULT NULL,
PRIMARY KEY (`b_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The most usual cause of this error is that the foreign key column definition does not match the definition of the referenced column. Another reason for the error is that the column referenced does not exist in the referenced table.
But the OP CREATE TABLE statements don't have that problem; those work with both MyISAM and InnoDB as default storage engine. (Not sure about any other storage engines, we don't see a storage engine specified, and I'm just guessing that the default is either InnoDB or MyISAM.)
SHOW VARIABLES LIKE 'default_storage_engine'
To debug this, try running the create table c WITHOUT the foreign key constraint definitions, and verify the table is created successfully. (The length modifier value of 255 strikes us as odd. Why not allow it to default to 11?)
CREATE TABLE c
( a_id INT COMMENT 'FK ref a.a_id'
, b_id INT COMMENT 'FK ref b.b_id'
, PRIMARY KEY (a_id, b_id)
);
Then try adding the foreign key constraints:
ALTER TABLE c ADD CONSTRAINT FK_c_a
FOREIGN KEY (a_id) REFERENCES a (a_id);
Ensure that column a_id exists in a, and that the definition matches. (Is it possible that the column is named id (rather than a_id) in table a?)
what is wrong?
mysql> create table price(
-> p_code char(1) not null,
-> p_description varchar(20),
-> p_rentfee decimal(2,2) not null,
-> p_dylatefee decimal(2,2));
Query OK, 0 rows affected (0.18 sec)
mysql> create table movie(
-> mv_no char(4) not null,
-> mv_name varchar(50) not null,
-> mv_year char(4) not null,
-> mv_cost decimal(2,2) not null,
-> mv_genre varchar(15) not null,
-> p_code char(1) not null,
-> foreign key (p_code) references price(p_code));
ERROR 1215 (HY000): Cannot add foreign key constraint
mysql>
price.p_code is not the primary key for price. Try:
create table price(
p_code char(1) not null PRIMARY KEY,
p_description varchar(20),
p_rentfee decimal(2,2) not null,
p_dylatefee decimal(2,2));
In general, foreign keys must reference a primary/unique key, a whole primary/unique key, and nothing but a primary/unique key.
In some RDBMS, for example SQL Server, you can reference a column with a unique index (not key) (see can we have a foreign key which is not a primary key in any other table?), but this is non-standard behavior.
Engine should be the same e.g. InnoDB
Datatype should be the same, and with same length. e.g. VARCHAR(20)
Collation Columns charset should be the same. e.g. utf8
Watchout: Even if your tables have same Collation, columns still could have different one.
Unique - Foreign key should refer to field that is unique (usually primary key) in the referenced table.
p_code should be a primary key in your price table:
create table price(
-> p_code char(1) not null,
-> p_description varchar(20),
-> p_rentfee decimal(2,2) not null,
-> p_dylatefee decimal(2,2),
-> PRIMARY KEY ( p_code ));
set p_code to be a key ,either set it to be a unique key or primary key.
The referenced column price.p_code must be unique (primary or unique key need to be created).
Both tables must be InnoDb tables, use ENGINE = INNODB in CREATE TABLE statement.
The data type for the child column must match the parent column exactly. For example, since price.p_code is an char(1), movie.p_code also needs to be an char(1) and price.p_code need be a Primary Key or need create a Index.