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.
Related
Table 1
create table personal(
id int not null auto_increment unique,
name char(20) not null,
age int not null,
city varchar(20) not null default 'Delhi'
);
insert into personal(name,age,city) values
('anubhav',22,'delhi'),
('rohit',24,'agra');
Table 2
create table applications(
app_id int(5) not null auto_increment unique,
city varchar(10) not null default 'Delhi'
);
insert into applications(city) values
('kolkata'),
('mumbai'),
('mumbai'),
('delhi'),
('agra'),
('agra');
Then i apply foreign key here with the help of Alter command-
alter table personal add foreign key(city) references applications(app_id)
but i am getting an error: ERROR 1005 (HY000): Can't create table 'student.#sql-f40_3' (errno: 150)
MySQL specifies:
Conditions and Restrictions
1.Corresponding columns in the foreign key
and the referenced key must have similar data types. The size and sign
of fixed precision types such as INTEGER and DECIMAL must be the same.
The length of string types need not be the same. For nonbinary
(character) string columns, the character set and collation must be
the same.
2.MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
The data type must be the same.
You could do:
alter table personal add foreign key(city) references applications(city)
But, the columns on both tables should be indexed.
See here
you desing in not normalized
your personal table should only reference the id.
City name in the applications should be unique, so i added it in the create table, there is no need for two or more delhis in a table(see normalisation)
If you really want to use in personal the city name, you must like i already made refernece the coty name of appcations or define a KEY for that column.
Further the datatyoes of the columns must always be the saem in both table for the foreign key
create table personal(
id int not null auto_increment unique,
name char(20) not null,
age int not null,
city int not null default 0
);
create table applications(
app_id int not null auto_increment primary key,
city varchar(10) not null unique default 'Delhi'
);
alter table personal add foreign key(city) references applications(app_id)
You have small bugs such as not putting null in the insert for the autoincrement and if it is primary key you should not put not null.
Table personal
create table personal(
id int auto_increment primary key,
name char(20) not null,
age int not null,
city varchar(20) not null default 'Delhi'
);
insert into personal values (null,'anubhav',22,'delhi'),
(null,'rohit',24,'agra');
Table applications
create table applications(
app_id int(5) auto_increment primary key,
city varchar(10) not null default 'Delhi'
);
insert into applications values(null,'kolkata'),
(null,'mumbai'),
(null,'mumbai'),
(null,'delhi'),
(null,'agra'),
(null,'agra');
Alter table
alter table personal add foreign key(city) references applications(app_id)
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)) ;
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.
> CREATE TABLE student(
-> student_id INT(2) NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> first_name VARCHAR(10),
-> last_name VARCHAR(10)
-> );
> CREATE TABLE course(
-> course_id CHAR(5) NOT NULL PRIMARY KEY,
-> course_name VARCHAR(50),
-> student_id INT(2) NOT NULL,
-> CONSTRAINT student_student_id_fk
-> FOREIGN KEY (student_id)
-> REFERENCES student(student_id)
-> );
Thats how i created two tables namely student and course. Then i entered data in the student table. But when i enter some invalid data in the course table, it doesn't gives me any error.
For example:
VALUES('A1','SUB 1',34);
gets the entry in the course table even if there is no primary key '34' in the student table.
Also, i can delete records in the student table, even if there is referential integrity.
So, how can enforce the constraints?
The easiest way to do this is to change your storage engine to InnoDB which supports the constraints.
For old MyISAM tables, you will have to use triggers on BOTH sides to enforce an FK relationship
Some links for self-help
http://dev.mysql.com/tech-resources/articles/mysql-enforcing-foreign-keys.html
http://forge.mysql.com/wiki/Triggers
Create your tables like this
> CREATE TABLE student(
-> student_id INT(2) NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> first_name VARCHAR(10),
-> last_name VARCHAR(10)
-> ) ENGINE = INNODB;
> CREATE TABLE course(
-> course_id CHAR(5) NOT NULL PRIMARY KEY,
-> course_name VARCHAR(50),
-> student_id INT(2) NOT NULL,
-> CONSTRAINT student_student_id_fk
-> FOREIGN KEY (student_id)
-> REFERENCES student(student_id)
-> ) ENGINE = INNODB;
For someone having the same problem, if you already created your table using MyISAM, you can change it to InnoDB using.
ALTER TABLE table_name ENGINE=InnoDB;