Why can't I reference a primary key? - mysql

The first two tables successfully pass, but as soon as the mysql checker reach the third table, it informs me that there is a problem with the reference key.
Here is my code:
CREATE TABLE USER(
Username VARCHAR(20) NOT NULL,
Email VARCHAR(50) NOT NULL,
Picture VARCHAR(30),
Points INT(5) DEFAULT 1 NOT NULL,
Password VARCHAR(50) NOT NULL,
Firstname VARCHAR(25) NOT NULL,
Lastname VARCHAR(25) NOT NULL,
PRIMARY KEY(Username)
);
CREATE TABLE THREAD (
ThreadID INT(9) NOT NULL AUTO_INCREMENT,
Title VARCHAR(255) NOT NULL,
PostID int(9) NOT NULL,
PRIMARY KEY (ThreadID)
);
CREATE TABLE POST(
ThreadID INT(9) NOT NULL,
PostID INT(9) NOT NULL AUTO_INCREMENT,
Content TEXT NOT NULL,
NumberOfLines INT(5) NOT NULL,
PRIMARY KEY(ThreadID, PostID),
FOREIGN KEY ThreadID(ThreadID) REFERENCES THREAD(ThreadID)
);
The error I am getting is the following:
#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 '
PRIMARY KEY(ThreadID, PostID),
FOREIGN KEY fk_ThreadID(ThreadID) REFE' at line 6
I tried creating the PRIMARY KEY(ThreadID, PostID) as separate entities, but this doesn't seem to work.
Thank you.

Adding to #Schwern, its giving error due to wrong usage of primary key. Below create table will work.
create table a (
id bigint(20) NOT NULL AUTO_INCREMENT,
col2 varchar(10), primary key (id, col2)
) engine=innodb;
So auto-increment column needs to be first one in the primary key.
We have extensively used this kind of primary key to partition the table on col2 - to range partition on a column, the column need to be part of primary key.
Also to mention, you can achieve additional unique key at the cost of an extra index

MySQL isn't being terribly informative there. SQLFiddle gives it straight.
Incorrect table definition; there can be only one auto column and it must be defined as a key
You can't have a multi-column key where one of them is AUTO_INCREMENT The AUTO_INCREMENT column must be first in a multi-column key in an InnoDB table. Either remove AUTO_INCREMENT from PostID, or make PostID alone the PRIMARY KEY and protect a post from appearing in the same thread twice with UNIQUE(ThreadID, PostID).
CREATE TABLE POST(
PostID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
ThreadID INT NOT NULL REFERENCES Thread(ThreadID),
Content TEXT NOT NULL,
NumberOfLines INT NOT NULL,
UNIQUE(ThreadID, PostID)
);
UPDATE: The best answer is #georgecj11's to put PostID first in the key as it only uses a single index.

Related

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'client_fk_name' in the referenced table 'client'

Why am I unable to add these foreign keys?
I'm trying to make clientName and employeeId both foreign keys in the events table. I realize I may not need clientEmail, but my error is currently showing at clientName.
CREATE TABLE client
(
clientName VARCHAR(50) PRIMARY KEY NOT NULL,
clientID INT NOT NULL auto_increment,
clientEmail VARCHAR(50) NOT NULL,
clientPass VARCHAR(50) NOT NULL,
phone VARCHAR(50) NOT NULL
);
CREATE TABLE admin
(
Name VARCHAR(50) NOT NULL,
adminId INT NOT NULL PRIMARY KEY auto_increment,
adminPass VARCHAR(50) NOT NULL,
adminEmail VARCHAR(50) NOT NULL
);
CREATE TABLE employee
(
Name VARCHAR(50) NOT NULL,
employeeId INT NOT NULL PRIMARY KEY auto_increment,
employeePass VARCHAR(50) NOT NULL,
employeeEmail VARCHAR(50) NOT NULL
);
CREATE TABLE event
(
eventId INT PRIMARY KEY auto_increment,
employeeId INT NOT NULL,
clientName VARCHAR(50) NOT NULL,
clientEmail VARCHAR(50) NOT NULL,
Constraint client_fk_name
Foreign Key (clientName)
references client (clientName),
Constraint client_fk_email
Foreign Key (clientEmail)
references client (clientEmail),
Constraint employee_fk_id
Foreign Key (employeeId)
references employee (employeeId)
);
Only these four tables.
So, one way to deal with this is to call the attribute in the parent table UNIQUE. This solves this error. However, as a side effect in my current experience, upon inserting into the database you may experience problems if your values are not unique (possibly obviously). But if you can guarantee uniqueness then just add Unique and you will be fine.
Unique specifies an attribute as a candidate key. Essentially it’s saying this could have been the primary key, but we chose something else.

errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps

sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:
Table users
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
cname varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
Table behaviours
CREATE TABLE behaviours (
id int(2) AUTO_INCREMENT PRIMARY KEY,
bName varchar(100) NOT NULL
);
Table severytys
CREATE TABLE severitys (
id int(2) AUTO_INCREMENT PRIMARY KEY,
severity varchar(10) NOT NULL
);
And here it shows errors:
CREATE TABLE child_behaviours(
id int(11) primary key auto_increment,
name varchar(50) not null,
cname varchar(50) not null,
bName varchar(100) NOT NULL,
severity varchar(10) NOT NULL,
start_at datetime,
stop_at datetime null,
FOREIGN KEY (id) REFERENCES users(id),
FOREIGN KEY (bName) REFERENCES behaviours(bName),
FOREIGN KEY (severity) REFERENCES severitys(severity)
);
Will be really pleasent to have an answer to this issue
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.
If you reference anything other than the PK, you need a really really good reason.
(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)
Now, child_behaviours has several errors:
Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.
Reference to behaviors(bName) instead of using its id
same thing for reference to severity
Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:
SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...
You have to refer to a primary key, when building a foreign key
CREATE TABLE child_behaviours(
userId int not null,
behaviourId int NOT NULL,
severityId int NOT NULL,
start_at datetime not null,
stop_at datetime,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
FOREIGN KEY (severityId) REFERENCES severitys(id)
);

Error code 1005 - Can't create table

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.

Having issues creating foreign keys

I have a table called member:
create table member(id int NOT NULL auto_increment PRIMARY KEY, name varchar(255) NOt NULL, email varchar(255) NOT NULL, userName varchar(255)
NOT NULL, password varchar(255) NOT NULL, handicap int);
and trying to create a table stableford which will have a foreign key name from the member table:
create table stableford(id int NOT NULL auto_increment PRIMARY KEY, title varchar(255) NOT NULL, player_name varchar(255) NOT NULL,
score int NOT NULL, INDEX(player_name), FOREIGN KEY(player_name) REFERENCES member(name));
Name of database is golfclub
I get an error cant create table 'golfclub.#sql-d1c_6' (errno:150)
Use the id on the member table as the foreign key and would be better to change it to something like membber_id. Here are references to help:
W3Schools foreign key constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
The error you are getting is because of following reasons:
The column name of table member you have referenced is not a primary key. So for adding a foreign key you have to reference the primary key of the referenced table which is id in this case. Go through this the documentation.
Syntax Error: You are missing the closing ) of second create statement.

MySQL creating a table (errno 150)

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