Key column doesn't exist in table - mysql

I'm having trouble adding a foreign key field that references another table.
First I created the users table as so:
CREATE TABLE users (
user_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
userName VARCHAR(256) NOT NULL,
userEmail VARCHAR (256) NOT NULL,
userPwd VARCHAR(256) NOT NULL,
);
then I'd like the quizzes table to have a foreign key that references the user_id from the first table
CREATE TABLE quizzes (
quizId INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
quizName VARCHAR(128) NOT NULL,
quizMax SMALLINT(6) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
This is throwing the error: 'Key column 'user_id' doesn't exist in table.
Other answers advised to check that DB is InnoDB, which I did, and it is.
Can't understand why it's telling me that user_id doesn't exist, when it clearly does exist in the users table.

Firstly check if table user is created successfully, due to the additional ',' on last column!
Secondly, the column you reffered in FOREIGN KEY(user_id) is not defined in table quizzes, you need to add this column in quizzes table.

First: You do not need the last comma - , in the first CREATE statement. -
Second: you have to create the columns before you can use them in a foreign key constraint and user_id does not exist in the second table at the moment of constraint creation.
Take a look at the example below. The last create succeeds when user_id column is added before the constraint is created:

Related

MySQL Using Same Foreign key for two different table columns

I found this thread similar to my query:
How to Link Foreign Key with Different Name
But unfortunately the answer to the question above doesn't resolve my problem as on my example tables, it doesn't create any primary key, all foreign keys only.
Here is the query for the table structure:
CREATE TABLE ref_data(
user_id INT(11) NOT NULL,
ref_id INT(11) NOT NULL,
ref_name VARCHAR(30) NOT NULL,
ref_date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT FK_user_id FOREIGN KEY(user_id) REFERENCES client (user_id),
CONSTRAINT FK_ref_id FOREIGN KEY(ref_id) REFERENCES client (user_id),
CONSTRAINT FK_ref_name FOREIGN KEY(ref_name) REFERENCES client (firstname)
);
I get the following error:
errno: 150 "Foreign key constraint is incorrectly formed"
Here I am using user_id twice, with the first as user_id and second as ref_id. I'm also using firstname as ref_name.
This is the client table:
CREATE TABLE client (
`user_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(30) NOT NULL UNIQUE KEY,
`email` VARCHAR(50) NOT NULL UNIQUE KEY,
`firstname` VARCHAR(30) NOT NULL,
`lastname` VARCHAR(30) NOT NULL,
`password` CHAR(128) NOT NULL
);
Ok, when trying to create the ref_data table, after the foreign key error, I see this:
LATEST FOREIGN KEY ERROR
------------------------ 2017-07-13 01:07:00 37ec Error in foreign key constraint of table ref_data:
FOREIGN KEY(ref_name) REFERENCES client (firstname) ):
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.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition. Create table 'test.ref_data'
with foreign key constraint failed. There is no index in the
referenced table where the referenced columns appear as the first
columns near ' FOREIGN KEY(ref_name) REFERENCES client (firstname) )'.
What that error is basically saying: (in the bold text)
There is no index on 'firstname' for the 'client' table (the portion after the REFERENCES clause of the FOREIGN KEY
But it's a simple fix. Run this SQL on the client table:
ALTER TABLE `client` ADD INDEX(`firstname`);
... and then run the ref_data table SQL again.

MySQL - How to create a foreign key between three tables

I have been set the task of creating 3 tables in MySql. One table called subjects with a field called subject_id as the primary key, another table called students with a field called student_id and a final table called entries.
The entries table must have two foreign keys, subject_id and student_id.
This is the official task:
Can anyone possibly help?
In your create table query after you define the column that will be your foreign key, simply write "Foreign Key - References -" and specify the column (where I wrote the first dash mark) you wish to connect to the other table. The second dash should be the table name followed by the column it references in parentheses.
If the table is already made, just use an alter table query and write "add foreign key - references -" with the same format as above.
Something like this
CREATE TABLE Subjects (
SubjectId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (SubjectId))
CREATE TABLE Students (
StudentId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (StudentId))
CREATE TABLE Entries(
EntriesId INT NOT NULL AUTO_INCREMENT,
SubjectId INT NOT NULL,
StudentId INT NOT NULL,
FOREIGN KEY (SubjectId) REFERENCES Subjects (SubjectId),
FOREIGN KEY (StudentId) REFERENCES Students (StudentId))

MySQL : Error Code 1215 : Cannot add foreign key constraint

I'm trying to make a simple SQL schema, but I'm having some problem with defining foreign keys. I really don't have that much MySQL knowledge, so I thought I'd ask her for some help. I get Error Code 1215 when I try to create the foreign key roomID and 'guestEmail' in the HotelManagement.Reservation table creation.
CREATE database HotelManagement;
CREATE TABLE HotelManagement.Room (
roomID INT not null auto_increment,
roomTaken TINYINT(1),
beds INT not null,
size INT not null,
roomRank INT not null,
PRIMARY KEY(roomID));
CREATE TABLE HotelManagement.HotelTask (
taskType INT not null,
taskStatus TINYINT(1) not null,
whichRoom INT not null,
note VARCHAR(255),
PRIMARY KEY (taskType),
FOREIGN KEY (whichRoom) REFERENCES HotelManagement.Room(roomID));
CREATE TABLE HotelManagement.Guest (
firstName varchar(25) not null,
lastName varchar(25) not null,
userPassword varchar(25) not null,
email varchar(25) not null,
reservation INT,
PRIMARY KEY (userPassword, email));
CREATE TABLE HotelManagement.Reservation (
reservationID INT not null,
id_room INT not null,
guestEmail varchar(25) not null,
fromDate DATE not null,
toDate DATE not null,
PRIMARY KEY (reservationID),
FOREIGN KEY (guestEmail)
REFERENCES HotelManagement.Guest(email),
FOREIGN KEY (id_room)
REFERENCES HotelManagement.Room(roomID)
);
ALTER TABLE HotelManagement.Guest
ADD CONSTRAINT res_constr FOREIGN KEY (reservation)
REFERENCES HotelManagement.Reservation(reservationID);
Updated the .sql
In the hoteltask table you have already defined a foreign key named roomid. Foreign key names also have to be unique, so just give a different name to the 2nd foreign key or omit the name completely:
If the CONSTRAINT symbol clause is given, the symbol value, if used,
must be unique in the database. A duplicate symbol will result in an
error similar to: ERROR 1022 (2300): Can't write; duplicate key in
table '#sql- 464_1'. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, a name for the constraint
is created automatically.
UPDATE
The email field in the guest table is the rightmost column of the primary key, this way the pk cannot be used to independently look up email in that table. Either change the order or fields in the pk, or have a separate index on email field in the guest table. Quote from the same link as above:
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.
Pls read through the entire documentation I linked before proceeding with creating the fks!
Side note 2 (1st is in the comments below): you should probably have a unique numeric guest id because that is lot more efficient than using email. Even if you decide to stick with email as id, I would restrict the pk in the guest table to email only. With the current pk I can register with the same email multiple times if I use different password.

One key as foreign key for multiple table

There are many similar question but this is bit different.
I have one table which has one foreign key that will reference to two tables.
I used below query for testing.
CREATE TABLE users
(
id int NOT NULL,
username varchar(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE admins
(
id int NOT NULL,
username varchar(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE info
(
id int NOT NULL,
fullname int NOT NULL,
user_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (user_id) REFERENCES admins(id)
);
Above queries works fine.
but when I try to draw model in mysql workbench it create on new field in info table that I don't want. I want user_id should work and show relation as foreign key for users and admins table.
One more thing, am I trying to do that is not well standard? Also suggests a correct way to do it.
Table names used only for example purpose. There is no logic here. I am trying to find solution for one key as foreign key for multiple table and faced issue with mysql work bench.
Try this:
Save your DDL in a file.
Create new model in MySQL Workbench
File > Import > Reverse Engineer MySQL Create Script
Browse to file created in step 1. Ensure that 'Place imported objects on diagram' is selected.
Click 'Execute'
From a data modelling point of view you might be better off specifying a user as an admin by including an extra column on the users table. Hence:
CREATE TABLE users
(
id int NOT NULL,
username varchar(255) NOT NULL,
isAdmin boolean not null default false,
PRIMARY KEY (id)
);
CREATE TABLE info
(
id int NOT NULL,
fullname int NOT NULL,
user_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id)
);

Mysql Foreign Key Usage

I'm trying my first hand at creating a mysql database for a simple blog. I'm having trouble understanding foreign keys and their appropriate relations. If someone can explain in "layman's" terms I'll be very happy.
I have a table called users that has the basics of fields (username, email, password etc) which I've created a user_type field and set it to INT. I've created the corresponding table called user_type and added two fields (one being the type_id = primary key and the other been the type = VARCHAR).
My question is:
Am I correct in understanding that I connect the two tables together by setting the foreign key link from the user_type INT in the users table to reference the type_id from the user_type table?
Your understanding is correct.
From SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
So in your example, the user_type id in table user_types would be the primary key, and the user_type int in table users would be the foreign key entry.
This enforces that an entry in table user_types has to exist before it can be used in table users.
You referencing from user to usertype:
n users have one user_type
If you create the table with an sql statement it should include something like this in the user part:
DROP TABLE IF EXISTS `user` ;
CREATE TABLE IF NOT EXISTS `user` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(55) NOT NULL ,
`email` VARCHAR(55) NOT NULL ,
`password` VARCHAR(55) NOT NULL ,
`user_type` INT NOT NULL ,
PRIMARY KEY (`ID`) ,
INDEX `user_to_usertype_idx` (`user_type` ASC) ,
CONSTRAINT `user_to_usertype`
FOREIGN KEY (`user_type` )
REFERENCES `user_type` (`type_id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
You have to create user_type before you create user, otherwise you will get a failure.