I am trying to create a series of tables using Foreign Keys of Primary Keys from other tables, however I always get the error
Table Creation Failed: Key column 'PACId' doesn't exist in table:
Here is the first case it appears:
CREATE TABLE PlantAreaCodes(
PACId INT NOT NULL AUTO_INCREMENT,
AreaCode INT,
AreaName CHAR(32),
Comments TEXT,
PRIMARY KEY (PACId)
);
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (MEId),
FOREIGN KEY (PACId)
REFERENCES PlantAreaCodes(PACId)
);
Is it to do with the syntax of the foreign key, or is it because the PACId is still empty, and cannot be?
It is not that PACId is empty. You haven't declared it in MajorEquipment.
Try using this definition for the second table:
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PACId INT, -- Added this column
PRIMARY KEY (MEId),
FOREIGN KEY (PACId)
REFERENCES PlantAreaCodes(PACId)
);
Here is a SQL Fiddle.
Try this
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (MEId),
PACId INT
REFERENCES PlantAreaCodes(PACId)
)
Related
Hello I have an issue when trying inserting multiple foreign keys to a table. I have searched a lot of hours and still I don't figure it out.. It pops this error. I don't know what else I can do about that. Also I tried to add constraint .. foreign key ... references command and it didn't work.
DROP DATABASE IF EXISTS db;
CREATE DATABASE db;
USE db;
CREATE TABLE BOOKS(
Bno int not null primary key auto_increment,
Title text,
PDate date,
Cno int,
Cname text
);
CREATE TABLE AUTHORS(
Ano int not null primary key auto_increment,
Asurname text,
Aname text
);
CREATE TABLE CATEGORIES(
Cno int not null primary key auto_increment,
Cname text,
No_Of_Books int
);
CREATE TABLE SUMMARY_LANG(
Bno int not null primary key auto_increment,
Language text,
FOREIGN KEY (Bno) REFERENCES BOOKS(Bno)
);
CREATE TABLE WRITER(
Bno int,
Ano int,
Asurname text,
Aname text,
FOREIGN KEY (Bno) REFERENCES BOOKS(Bno),
FOREIGN KEY (Ano) REFERENCES AUTHORS(Ano),
FOREIGN KEY (Asurname) REFERENCES AUTHORS(Asurname),
FOREIGN KEY (Aname) REFERENCES AUTHORS(Aname)
);
INSERT INTO BOOKS(Title,PDate,Cname)
VALUES
('A first course in database systems','2014-01-01','DATABASE'),
('FUNDAMENTAL CONCEPTS OF PROGRAMMING SYSTEMS','1976-01-01','PROGRAMMING');
ALTER TABLE AUTHORS auto_increment = 100;
INSERT INTO AUTHORS(Asurname,Aname)
VALUES
('ULLMAN','JEFF'),
('WIDOM','JENNIFER');
ALTER TABLE CATEGORIES auto_increment = 10;
INSERT INTO CATEGORIES(Cname, No_Of_Books)
VALUES
('DATABASE',1),
('PROGRAMMING',1);
INSERT INTO SUMMARY_LANG(Language)
VALUES
('ENG'),
('GRE'),
('ENG'),
('FRA');
Your definition of SUMMARY_LANG is wrong
CREATE TABLE SUMMARY_LANG(
Bno int not null primary key auto_increment,
Language text,
FOREIGN KEY (Bno) REFERENCES BOOKS(Bno) <-- remove this reference
);
Remove the foreign key, because this is a Table that is used only as reference number to another table also called a helper table, because the text would be redundant in the referenced table.
But i can't see any column that references language.
So add a column to BOOKS, where you add the reference to SUMMARY_LANG and when you add new rows SUMMARY_LANG you won't get any errors anymore.
So the new tables can be like this
CREATE TABLE BOOKS (
Bno INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Title TEXT,
PDate DATE,
Cno INT,
Cname TEXT,
SNno int,
FOREIGN KEY (SNno)
REFERENCES SUMMARY_LANG (SNno)
);
CREATE TABLE SUMMARY_LANG(
SNno int not null primary key auto_increment,
Language text
);
trying the following code:
create table donation(
donation_number int not null primary key ,
product_id int not null
);
create table stock (
product_id int not null primary key,
available_qty int not null,
FOREIGN KEY (product_id ) REFERENCES donation(product_id)
);
Give back
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'stock_ibfk_1' in the referenced table 'donation'.
Why? how can I solve this problem?
to create a foreign key relationship, the parent table column on which you are creating relation must be unique or primary and they must have the same datatype and size also
product_id in donation table is not unique.
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'm using an a mySQL db on localhosts. Created table with primary key and another table with foreign key pointing to that one, but when I want to see the results all I geted is "alert" that MySQL returned emty result. Here my tables
CREATE TABLE example_1(
ex1_id int NOT NULL AUTO_INCREMENT,
first_name varchar(50) NULL,
last_name varchar(50) NULL,
CONSTRAINT example_1_pk PRIMARY KEY (ex1_id)
);
CREATE TABLE example_2 (
ex2_id int NOT NULL AUTO_INCREMENT,
acces_lvl int NOT NULL,
CONSTRAINT example_2_pk PRIMARY KEY (ex2_id)
);
CREATE TABLE example_3 (
ex3_id int NOT NULL AUTO_INCREMENT,
first int NOT NULL,
second int NOT NULL,
CONSTRAINT example_3_pk PRIMARY KEY (ex3_id),
FOREIGN KEY (first) REFERENCES example_1(ex1_id),
FOREIGN KEY (second) REFERENCES example_2(ex2_id)
);
Then I add something to db, eg.
INSERT INTO `example_1`(`first_name`, `last_name`) VALUES ('foo', 'bar');
and
INSERT INTO `example_2`(`acces_lvl`) VALUES (2)
then when I try
SELECT * FROM `example_3`
I have nothing, empty results. Shouldn't be there id's from other tables? Am I doing something wrong, or I didn't do something? I'm totally noob in database.
Because you did not insert any data into example_3. Foreign key constraints don't propagate data, they just enforce the data relationship, so when you do insert data into example_3, the values you put in the columns with foreign key constraints have corresponding values in other table.
Hello i have a table which has one primary key by the name of ImageID and i want to make another column
also primary key which is PropertyID means Composite Key
HERE IS THE CODE, but its showing this error for me "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( PropertyID INT, ImageID INT primary key (PropertyID, ImageID) )' at line "
Also the ImageID is already primary key, but with varchar(15) specification.
Alter TABLE properties (
PropertyID INT,
ImageID INT,
primary key (PropertyID, ImageID)
);
Each table can only have 1 primary key. You can only have one primary key, but you can have multiple columns in your primary key.
Taken from W3Schools:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
Here the only primary key is pk_PersonID but that have stated that pk_PersonID is made up of P_Id and LastName.
Unique Indexes may be what you're looking for. This means unique values are required and runs like an index in that it can speed up queries.
Try this:
First drop the existing primary key
ALTER TABLE properties
DROP PRIMARY KEY;
Then add composite key
ALTER TABLE properties
ADD PRIMARY KEY(imageID, propertyID);
As I understand you already have a table with one key, which looks like the following:
CREATE TABLE `common`.`properties` (
`PropertyID` VARCHAR(15) NOT NULL,
`otherColumn` VARCHAR(45) NULL,
PRIMARY KEY (`PropertyID`));
And now you want to add another PK column and change the type of existing PK column from char to INT. So you need to do it as following:
ALTER TABLE `common`.`properties`
CHANGE COLUMN `PropertyID` `PropertyID` INT NOT NULL ,
ADD COLUMN `ImageID` INT NOT NULL AFTER `otherColumn`,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`PropertyID`, `ImageID`);
P.S. common is my schema name, you can use your own, or even skip it if your schema is default.