Hi I'm having issues creating my post database. I'm trying to make a forenge key to link to my users database. Can someone please help?
Here's the code for my tables :
CREATE TABLE USERS(
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID,UserName)
)ENGINE=InnoDB;
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB;
Here's the last InnoDB error message:
Error in foreign key constraint of table db/POSTS:
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB:
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.
There really should not be a good reason to have a compound primary key on the first table. So, I think you intend:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID),
UNIQUE (UserName)
);
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserId)
);
Some notes:
An auto-incremented id is unique on every row. It makes a good primary key.
A primary key can consist of multiple columns (called a composite primary key). However, an auto-incremented id doesn't make much sense as one of the columns. Just use such an id itself.
If you use a composite primary key, then the foreign key references need to include all columns.
I chose UserId for the foreign key reference. You could also use UserName (because it is unique).
UserName is a bad choice for foreign keys, because -- conceivably -- a user could change his or her name.
The error is caused by incorrect foreign key definition. In the concrete case you are missing a complete column in your foreign key definition.
In the USERS table you have defined primary key as composite key of UserID and UserName columns.
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID,UserName)
) ENGINE=InnoDB;
note that it is good practice to respect case of the identifiers (column names)
In the POSTS table you declared your foreign key to reference only one column in the USERS table, the UserName column. This is incorrect as you need to reference entire primary key of the USERS table which is (UserID, UserName). So to fix the error you need to add one additional column to the POSTS table and change your foreign key definition like this:
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
authorId int,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(authorId, postAuthor) REFERENCES USERS(UserID, UserName)
) ENGINE=InnoDB;
Please look at following fiddle: http://sqlfiddle.com/#!9/92ff1/1
NOTE: If you can you should re-architect this to not use the composite primary key in the USERS table as it does not make sense from what I can see in the displayed code. You can change the tables like this:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID)
) ENGINE=InnoDB;
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthorID int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthorID) REFERENCES USERS(UserID)
) ENGINE=InnoDB;;
Related
CREATE TABLE category(
id int(10) NOT NULL AUTO_INCREMENT,
entity_type varchar(32),
entity_id INT(10),
PRIMARY KEY (id),
FOREIGN KEY (entity_id)
)
I get an error
You have an error in your SQL syntax; it seems the error is around: '
entity_id INT(10), PRIMARY KEY (id), FOREIGN KEY (entity_id) )' at
line 3
I am unable to understand on how to fix it.
Whereas when I add this
CREATE TABLE `Image` (
`Id [PK]` int (10) ,
`EntityType` varchar(32),
`EntityId [FK]` int(10)
);
the above code fixes the error
Below is the code which gives Foreign key constraints even after I tried creating image and category table first and then adding relation to it in the User Table
$sql_image = 'CREATE TABLE IF NOT EXISTS image (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) )';
if ($db->database->createTable($sql_image)) { echo "Image Table Created Successfully"; }
$sql_category = 'CREATE TABLE IF NOT EXISTS category (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );';
if ($db->database->createTable($sql_category)) {
echo "Category Table Created Successfully"; }
$sql_user = 'Create TABLE IF NOT EXISTS user(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10),
status boolean,
user_profile_photo int(10),
FOREIGN KEY (user_profile_photo) references image(entity_id),
FOREIGN KEY (category) references category(entity_id) );';
if ($db->database->createTable($sql_user)) {
echo "User Table Created Successfully"; }
If you want a foreign key to be added then you need to define the reference table means in which table the entity_id belongs
CREATE TABLE category(
id int(10) NOT NULL AUTO_INCREMENT,
entity_type varchar(32),
entity_id INT(10),
PRIMARY KEY (id),
FOREIGN KEY (entity_id) REFERENCES Entity(entity_id)
)
The last line it's wrong.
Try something like this:
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)'
FOREIGN KEY (product_category, product_id)
REFERENCES second_table(category, id)
2 errors that I can see
1) 'MySQL requires indexes on foreign keys and referenced keys'. MySQL will create keys on the referencing table(users) if you do not but you have to create them on the referenced tables on entity_id(image,category)
2) 'Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same'
see https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
This syntaxs and generates the tables (you need to decide what kind of key k1 and k2 should be):-
drop table if exists us;
drop table if exists i;
drop table if exists c;
CREATE TABLE IF NOT EXISTS i (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );
alter table i
add key k1(entity_id);
CREATE TABLE IF NOT EXISTS c (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );
alter table c
add key k2(entity_id);
Create TABLE IF NOT EXISTS us(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10) unsigned,
status boolean,
user_profile_photo int(10) unsigned,
FOREIGN KEY fk1(user_profile_photo) references i(entity_id),
FOREIGN KEY (category) references c(entity_id)
);
Verify that both table columns are defined with same data type.
Verify that both table and their columns have same collation charset should be same e.g. utf-8
Even if tables have same collation , columns still could have different one.
Verify that both columns have the same signing definition. If the referencing column is int(10) unsigned so should be the referencing
column.
In my case
column user_profile_photo from user table and id from image table were having different signing definition. hence it was not adding foreign key.
FOREIGN KEY (user_profile_photo) references image(id),
FOREIGN KEY (category) references category(id)
$sql_image = 'CREATE TABLE IF NOT EXISTS image (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, // int(10) UNSIGNED should be same as that in user table below.
entity_type VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
)';
if ($db->database->createTable($sql_image)) {
echo "Image Table Created Successfully<br><br>";
}
$sql_category = 'CREATE TABLE IF NOT EXISTS category (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, // int(10) UNSIGNED should be same as that in user table below.
entity_type VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
);';
if ($db->database->createTable($sql_category)) {
echo "Category Table Created Successfully<br><br>";
}
$sql_user = 'CREATE TABLE IF NOT EXISTS user(
id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10) UNSIGNED NOT NULL, //int(10) UNSIGNED should be match id from category table.
status boolean,
user_profile_photo int(10) UNSIGNED NOT NULL,
FOREIGN KEY (user_profile_photo) references image(id),
FOREIGN KEY (category) references category(id)
);';
if ($db->database->createTable($sql_user)) {
echo "User Table Created Successfully<br><br>";
}
I am having a problem trying to load my database into MySQL as I am having a few errors with my foreign keys. Things I have tried to do to fix this issue is:
- Putting foreign keys after the primary keys
Eg:
CREATE TABLE IF NOT EXISTS Passenger (
.......
PRIMARY KEY(tNum),
FOREIGN KEY (fNum) REFERENCES Flights(fNum),
FOREIGN KEY (fDate) REFERENCES Flights(fDate),
FOREIGN KEY (sCity) REFERENCES Flights(sCity),
FOREIGN KEY (eCity) REFERENCES Flights(eCity)
);
- Bunching the foreign keys in the format of
Eg:
ALTER TABLE Passenger ADD FOREIGN KEY (fNum, fDate, sCity, eCity) REFERENCES Flights(fNum, fDate, sCity, eCity);
The error I get is:
1005 - Can't create table 'airline.#sql-1d7_7c' (errno: 150)
My full code is:
DROP DATABASE IF EXISTS airline;
CREATE DATABASE IF NOT EXISTS airline;
USE airline;
CREATE TABLE IF NOT EXISTS Flights (
fNum char(6) not null,
pID char(4) not null,
fDate DATE not null,
eDate DATE not null,
sTime char(4) not null,
lTime char(4) not null,
sOStart char(4) null,
sOEnd char(4) null,
sCity varchar(30) not null,
eCity varchar(30) not null,
sOCity varchar(30),
sNum char(5) not null,
PRIMARY KEY (fNum)
);
CREATE TABLE IF NOT EXISTS Passenger (
tNum char(4) not null,
dPurch DATE not null,
pMethod varchar(30) not null,
fNum char(6) not null,
fDate DATE not null,
sCity varchar(30) not null,
eCity varchar(30) not null,
tType varchar(30) not null,
Price decimal(4,2) not null,
iType varchar(30) not null,
idNum char(8) not null,
fName varchar(30) not null,
lName varchar(30) not null,
Sex char(1) not null,
pAddress varchar(30) not null,
pPhone char(8) not null,
pEmail varchar(30) not null,
PRIMARY KEY(tNum)
);
CREATE TABLE IF NOT EXISTS Planes (
pID char(4) not null,
pType char(3) not null,
pDesc varchar(30) not null,
pRange char(4) not null,
Capacity char(3) not null,
mDate DATE not null,
pDate DATE not null,
sDate DATE not null,
PRIMARY KEY (pID)
);
CREATE TABLE IF NOT EXISTS Staff (
sNum char(5) not null,
sName varchar(30) not null,
sDOB DATE not null,
sAddress varchar(30) not null,
pCompany varchar(30) ,
pStart DATE ,
pEnd DATE ,
jID char(1) not null,
PRIMARY KEY (sNum)
);
CREATE TABLE IF NOT EXISTS Emergency (
eID char(5) not null,
sNum char(5) not null,
eName varchar(30) not null,
eAddress varchar(30) not null,
ePhone char(8) not null,
eEmail varchar(30) not null,
eRelationship varchar(30) not null,
PRIMARY KEY(eID)
);
CREATE TABLE IF NOT EXISTS Pilot (
sNum char(5) not null,
pID char(4) not null,
cDate DATE not null,
jID char(1) not null,
PRIMARY KEY(jID)
);
CREATE TABLE IF NOT EXISTS Attendant (
sNum char(5) not null,
tSDate Date not null,
tFDate Date not null,
tDesc Varchar(30) not null,
jID Char(1) not null,
PRIMARY KEY(jID)
);
ALTER TABLE Flights ADD FOREIGN KEY (pID) REFERENCES Planes(pID);
ALTER TABLE Flights ADD FOREIGN KEY (sNum) REFERENCES Staff(sNum);
ALTER TABLE Passenger ADD FOREIGN KEY (fNum) REFERENCES Flights(fNum);
ALTER TABLE Passenger ADD FOREIGN KEY (fDate) REFERENCES Flights(fDate);
ALTER TABLE Passenger ADD FOREIGN KEY (sCity) REFERENCES Flights(sCity);
ALTER TABLE Passenger ADD FOREIGN KEY (eCity) REFERENCES Flights(eCity);
ALTER TABLE Emergency ADD FOREIGN KEY (sNum) REFERENCES Staff(sNum);
ALTER TABLE Pilot ADD FOREIGN KEY (sNum) REFERENCES Staff(sNum);
ALTER TABLE Pilot ADD FOREIGN KEY (pID) REFERENCES Planes(pID);
ALTER TABLE Pilot ADD FOREIGN KEY (jID) REFERENCES Staff(jID);
ALTER TABLE Attendant ADD FOREIGN KEY (sNum) REFERENCES Staff(sNum);
ALTER TABLE Attendant ADD FOREIGN KEY (jID) REFERENCES Staff(jID);
For me this is the one it fails on first
ALTER TABLE Passenger ADD FOREIGN KEY (fDate) REFERENCES Flights(fDate);
Try adding an index on Flights.fdate first, then doing the foreign key and doing that for additional references until it works. Let me know if that works for you, it did for me.
By the way you might want to reconsider your schema there. Joins and relations should really be done on integers only. That schema will bog down fast as it grows. Also, and maybe this is just personal preference but I prefer first_name to fName. Easier to read for other developers, this isn't 1986, we can have human readbable names now :-)
I have an issue that I can't figure out for the life of me. I have been creating an application in PHP/MySQL on windows using XAMPP but now I am trying to test it on a Linux based LAMP server and I get the following error when trying to create a table with foreign key constraints:
"3 - photoProjectItem table creation: Cannot add foreign key constraint"
When I run the code on XAMPP in Windows it works fine, but not within Linux. These are the tables I am trying to create:
CREATE TABLE IF NOT EXISTS generalSecurity(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
firstname VARCHAR(100) NOT NULL,
secondname VARCHAR(100) NOT NULL,
accessLevel ENUM('admin', 'contributer', 'subscriber') NOT NULL,
Email VARCHAR (200) UNIQUE NOT NULL
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS generalSiteInfo (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
siteName VARCHAR(100) NOT NULL,
siteOwnerID INT(10) UNSIGNED NOT NULL,
INDEX par_id4(siteOwnerID),
FOREIGN KEY(siteOwnerID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
siteEmail VARCHAR(100) NOT NULL,
siteAbout VARCHAR(9999) NOT NULL,
currentTheme VARCHAR(1000) NOT NULL,
siteCreateDate TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Project (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
projectAuthorID INT(10) UNSIGNED NOT NULL,
INDEX par_id(projectAuthorID),
FOREIGN KEY(projectAuthorID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
projectName VARCHAR(100) NOT NULL,
projectBlurb VARCHAR(5000) NULL,
projectTheme VARCHAR(100) NOT NULL,
projectDate TIMESTAMP
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS ProjectItem (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
authorID INT(10) UNSIGNED NOT NULL,
INDEX par_id2(authorID),
FOREIGN KEY(authorID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
projectID INT(10) UNSIGNED NOT NULL,
INDEX par_id3(projectID),
FOREIGN KEY(projectID)
REFERENCES project(id)
ON DELETE CASCADE,
itemType ENUM('image', 'text') NOT NULL,
photoFileName VARCHAR(100) NULL,
itemName VARCHAR(1000) NOT NULL,
entry VARCHAR(5000) NULL,
photoMeta VARCHAR(5000) NOT NULL,
date TIMESTAMP,
deleted BOOLEAN NOT NULL
) ENGINE=INNODB;
it fails when trying to create table "ProjectItem". Can you guys see anything I am missing?
I really appreciate any help that can be given
---edit---
it works when I remove the lines
INDEX par_id3(projectID),
FOREIGN KEY(projectID)
REFERENCES project(id)
ON DELETE CASCADE,
but I can't see any obvious issues with the relationship
The issue was that apparantly MYSQL in Linux is case sensitive whereas in Windows it doesn't appear to be. I was trying to create a relationship for the table "project" when it is called "Project"
I am creating three tables and when trying to tie the primary and foreign keys I am receiving the error message "Key column 'username' doesn't exist in table".
Could someone take a look at my code and tell me what I am doing wrong? I have tried dropping the database and revamped the tables a few times but I am still getting the same message. Here is my code, thank you in advance for any help!
create database testproject
use testproject
create table caller_info
(
caller_id int(11) unsigned auto_increment primary key not null,
first_name varchar(35) not null,
Last_name varchar(35) not null,
phone_number int(25) not null
);
create table caller_call_record
(
call_record_id int(11),
Call_Description varchar(50),
franchise_id int(10) not null,
email varchar(40) not null,
username varchar(25) primary key not null
);
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) not null,
PRIMARY KEY(call_escalation_id),
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY(username) REFERENCES caller_call_record(username)
);
As pointed out, your table caller_escalation needs a column called username in order to create the foreign key.
It sounds like once you've added that, you're now getting a Cannot add foreign key constraint error from MySQL. The first thing that comes to mind with this kind of error is that you're using the wrong engine for your tables. You are most likely using MyISAM which does not support foreign key references - in order to use these, you will need to change the engine on all of your tables to InnoDB.
try this:
create table caller_call_record
(
call_record_id int(11),
Call_Description varchar(50),
franchise_id int(10) not null,
email varchar(40) not null,
username varchar(25) not null,
PRIMARY KEY (username)
);
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) not null,
username varchar(25) not null,
PRIMARY KEY(call_escalation_id,username),
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY(username) REFERENCES caller_call_record
);
The table caller_escalation also needs a column username, which is not there
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) unsigned not null, ;; <--- added unsigned type here
PRIMARY KEY(call_escalation_id),
username varchar(25) not null, ;; <--- added field here
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY (username) REFERENCES caller_call_record (username)
);
Also ensure the column data types are the same in both tables. You have "caller_id int(11) unsigned" in caller_info and "caller_id int(11)" in caller_escalation. I added the unsigned specifier above to make it work.
hey guys, i'm getting this error.
Error 1452 : Cannot add or update a child row: a foreign key constraint fails (`s2794971db/ProfileInterests`, CONSTRAINT `ProfileInterests_ibfk_2` FOREIGN KEY (`InterestID`) REFERENCES `Interests` (`ID`))
I change my tables from myISAM to innodb...found out I needed to so that delete was easier.
I had issues with it so I deleted the table which I needed to create the relationships with.
Then I made it again
I originally had
create table if not exists Users (
ID int not null auto_increment primary key,
FirstName varchar(40) not null,
LastName varchar(40) not null,
UserName varchar(40) not null,
UserEmail varchar(40) not null,
UserDOB timestamp not null,
UserJoin datetime not null
);
create table if not exists Interests(
ID int not null auto_increment primary key,
Interests varchar(40) not null
);
create table if not exists ProfileInterests (
userID int not null References Users(ID),
InterestID int not null References Interests(ID),
MiddleID int not null auto_increment primary key
);
but then I deleted the last table and made it
create table if not exists ProfileInterests (
userID int not null,
InterestID int not null,
MiddleID int not null auto_increment primary key
);
and then I made userID and InterestID into index's and then I added a relation User-> ID for userID and interests->ID for interestID
the error occurs when i'm trying to input data into via a php form.
Any ideas...really need some help!
Obviously, you're trying to insert a record into ProfileInterests for which there is no matching record in the Interests table. Look at the exact insert query, and check that you're supplying a valid value for every field in the table which is part of a foreign key relationship.