MYSQL Foreign Key, Cant create table (errno:150) - mysql

I am trying to build the database and tables for my system. But I found that if I don't add the foreign key in the codes. There is no error. I've used many method try to make the codes works, but it still have error.
Create table if not exists users_details_one
(
fname varchar(255),
lname varchar(255),
address varchar(255),
users_email varchar(255),
users_password varchar(255),
department varchar(255)
);
Create table if not exists users_one
(
users_email varchar(255),
users_password varchar(255) ,
FOREIGN KEY (users_email) REFERENCES users_details_one(users_email),
FOREIGN KEY (users_password) REFERENCES users_details_one(users_password)
);

There's a typo in your foreign key:
FOREIGN KEY (users_password) REFERENCES users_details_one(users_spassword) should be FOREIGN KEY (users_password) REFERENCES users_details_one(users_password)
and you also need indexes on users_email and users_password in table users_details_one, such as this:
Create table if not exists users_details_one
(
fname varchar(255),
lname varchar(255),
address varchar(255),
users_email varchar(255),
users_password varchar(255),
department varchar(255),
index (users_email),
index (users_password)
);
Create table if not exists users_one
(
users_email varchar(255),
users_password varchar(255) ,
FOREIGN KEY (users_email) REFERENCES users_details_one(users_email),
FOREIGN KEY (users_password) REFERENCES users_details_one(users_password)
);
it is not necessary for the index to be unique.
from the manual
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.

If you want to make a column as a foreign key, those columns must be either primary keys aur must have a uniqueness constraint i.e. in your case the users_email and users_password of users_details_one must be unique or primary keys.

Related

Im getting an error code 1822 when i making the TAG table

create database priceTag;
use priceTag;
CREATE TABLE `ProductNumber` (
`Sku` INT auto_increment not null,
`Model` VARCHAR(100),
PRIMARY KEY (`Sku`)
);
ALTER TABLE ProductNumber AUTO_INCREMENT=60000;
CREATE TABLE `Manufacture` (
`Manufacture` VARCHAR(100),
`Model` VARCHAR(100),
`Category` VARCHAR(100),
PRIMARY KEY (`Model`)
);
CREATE TABLE `OpenBox` (
`Condtion` VARCHAR(100),
`LP` INT auto_increment not null,
`MissingItems` VARCHAR(100),
`Model_` VARCHAR(100),
FOREIGN KEY (`Model_`) REFERENCES `Manufacture`(`Model`),
PRIMARY KEY (`LP`)
);
ALTER TABLE OpenBox AUTO_INCREMENT=200000000;
CREATE TABLE `TAG` (
`SKU*` INT,
`Model*` VARCHAR(100),
`PRICE*` DECIMAL(10,2),
`LP*` INT,
`condtion*` VARCHAR(100),
FOREIGN KEY (`SKU*`) REFERENCES `ProductNumber`(`Sku`),
FOREIGN KEY (`Model*`) REFERENCES `Manufacture`(`Model`),
FOREIGN KEY (`LP*`) REFERENCES `OpenBox`(`LP`),
FOREIGN KEY (`condtion*`) REFERENCES `OpenBox`(`condtion`)
);
CREATE TABLE `Inventory` (
`INV` int,
`Sku!` int,
`Model!` VARCHAR(100),
FOREIGN KEY (`Sku!`) REFERENCES `ProductNumber`(`Sku`),
FOREIGN KEY (`Model!`) REFERENCES `Manufacture`(`Model`)
);
The column which you refer on in FOREIGN KEY (`condtion*`) REFERENCES `OpenBox`(`condtion`) (i.e. OpenBox.condtion) is not indexed.
Add needed unique index creation then create TAG table.
DEMO
I tested your code, and then ran SHOW ENGINE INNODB STATUS to get more detailed information about the error.
LATEST FOREIGN KEY ERROR
2021-12-02 09:47:16 0x700007565000 Error in foreign key constraint of table test2/tag:
FOREIGN KEY (condtion*) REFERENCES OpenBox(condtion)
):
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.
It's complaining about this foreign key:
FOREIGN KEY (`condtion*`) REFERENCES `OpenBox`(`condtion`)
The OpenBox.condtion column is not a primary key or unique key. Foreign keys must reference a key of the parent table.
You already have another foreign key in your TAGS table referencing the OpenBox table. Are you intending that the condtion column of the respective row be copied to the TAGS table? That's not how foreign keys are intended to be used.

How to use a Foreign key in a table a primary key in another table

I have 3 tables. Courses,CourseDestails, CourseBooking.
Courses
CREATE TABLE Courses (
courseId int NOT NULL,
courseName varchar(255),
level varchar(255),
description varchar(255),
PRIMARY KEY (courseId)
);
CourseDetails
CREATE TABLE CourseDetails (
CourseStartDate int NOT NULL,
Location varchar(255) NOT NULL,
MaxNoPlaces int,
Length int,
Instructor varchar(255),
TotalPlacesBooked int,
NoPlacesCancelled int,
AdultPrice int,
ChildPrice int,
courseId int,
CONSTRAINT PK_CourseDetails PRIMARY KEY (CourseStartDate,Location,courseId),
FOREIGN KEY (courseId) REFERENCES Courses(courseId)
);
courseId from courses table is used as foreign key in the CourseDetails table.
Now I want to use CourseStartDate Location & courseId from CourseDetails table in another table called CourseBooking. I know how to add CourseStartDate Location as foreign keys. But I'm confused how to add courseId from courseDetails table as foreign key in the new CourseBookings Table.
I have tried the following
CREATE TABLE CourseBookings (
CourseStartDate int NOT NULL,
Location varchar(255) NOT NULL,
GuestNo int,
courseId int,
CONSTRAINT PK_CourseDetails PRIMARY KEY (CourseStartDate,Location,GuestNo,courseId),
FOREIGN KEY (courseId) REFERENCES CourseDetails.courseId(courseId),
FOREIGN KEY (CourseStartDate) REFERENCES CourseDetails(CourseStartDate),
FOREIGN KEY (Location) REFERENCES CourseDetails(Location),
FOREIGN KEY (GuestNo) REFERENCES Guest(GuestNo)
);
But there is an error saying
Can't create table 'b8040777_db1.CourseBookings'
Supports transactions, row-level locking, and foreign keys
There are several issues with the declaration of table CourseBookings.
ISSUE 1
This :
FOREIGN KEY (courseId) REFERENCES CourseDetails.courseId(courseId),
Should be written as :
FOREIGN KEY (courseId) REFERENCES CourseDetails(courseId),
ISSUE 2
One of the columns of CourseDetails, that is referenced by a foreign key of table CourseBookings, has no index.
From the documentation :
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.
In table CourseDetails :
courseId had an index automatically created because it references Courses(courseId)
CourseStartDate has no index but it is the first column in the index automatically generated by the primary key constraint declaration
Location has no index and it is only the second column in the primary key index --> it is not possible to create a foreign key referencing it, an error is raised when you try
SOLUTION 1
It is always possible to add the missing index to the table, by adding this to the CREATE TABLE CourseDetails statement :
INDEX idx_Location (Location)
SOLUTION 2
In your use case, I suspect that what you actually need is a multicolumn foreign key (supported in InnoDB only), that references the primary key of CourseDetails (an index already exists on these columns). This will allow you to associate each record of CourseBookings with a unique parent record in CourseDetails.
Suggestion of DDL :
CREATE TABLE CourseBookings (
CourseStartDate int NOT NULL,
Location varchar(255) NOT NULL,
GuestNo int,
courseId int,
CONSTRAINT PK_CourseDetails PRIMARY KEY (CourseStartDate,Location,courseId,GuestNo),
FOREIGN KEY (CourseStartDate,Location,courseId)
REFERENCES CourseDetails(CourseStartDate,Location,courseId),
FOREIGN KEY (GuestNo) REFERENCES Guest(GuestNo)
);
SOLUTION 3
If solution 2 fits for your use case, then it means that your schema can be optimized by creating an autoincremented integer primary key on table CourseDetails. The existing primary key can be turned into a UNIQUE constraint. Then, in table CourseBookings, you can just store a foreign key to that column.
This would give you a simple and efficient way to relate one table to the other, while avoiding duplicating information across tables (this actually leaves you with just 3 columns in CourseBookins).
In relational database design it is usually a good practice to create such a primary key on most tables. You could consider adding one to other tables too.
Example :
CREATE TABLE CourseDetails (
id int PRIMARY KEY AUTO_INCREMENT,
CourseStartDate int NOT NULL,
...
CONSTRAINT PK_CourseDetails UNIQUE (CourseStartDate,Location,courseId),
FOREIGN KEY (courseId) REFERENCES Courses(courseId)
);
CREATE TABLE CourseBookings (
id int PRIMARY KEY AUTO_INCREMENT,
courseDetailId INT NOT NULL,
GuestNo int,
CONSTRAINT PK_CourseBookings UNIQUE (courseDetailId,GuestNo),
FOREIGN KEY (courseDetailId) REFERENCES CourseDetails(id),
FOREIGN KEY (GuestNo) REFERENCES Guest(GuestNo)
);
PS, just in case :
FOREIGN KEY (GuestNo) REFERENCES Guest(GuestNo)
Does table Guest exists in your schema (you did not show the CREATE TABLE for it) ?

many to many relationship in MySQL

I have this entity relationship:
I want to save information about the current team and the last teams, also I save the different positions in each team.
I create this tables:
table of player:
create table player(
codPlayer varchar(12) primary key,
name varchar(30) unique not null,
codCurrentTeam varchar(12),
position varchar(20),
foreign key (codCurrentTeam) references team(codTeam)
);
table of team:
create table team(
codTeam varchar(12) primary key,
name varchar(40) unique not null
);
table of lastTeam:
create table lastTeam(
startDate date,
finishDate date,
codTeam varchar(12),
codPlayer varchar(12),
constraint pkLastTeam primary key (codTeam,codPlayer),
foreign key (codTeam) references team(codTeam),
foreign Key (codPlayer) references jugador (codPlayer)
);
table of positions:
create table position(
codPlayer varchar(12),
codLastTeam varchar(24),
position varchar(20),
primary key (codPlayer, codLastTeam),
foreign key (codPlayer) references jugador(codPlayer),
foreign key (codLastTeam) references lastTeam(pkLastTeam)
);
I can create all tables except position, mysql returns the next error:
Error Code: 1215. Cannot add foreign key constraint
perhaps my diagram have some mistakes, but I don't know how to implement the design
the issue is you dont have
create table position "pkLastTeam" column in lastTeam t
codPlayer varchar(12),
codLastTeam varchar(24),
position varchar(20),
primary key (codPlayer, codLastTeam),
foreign key (codPlayer) references jugador(codPlayer),
foreign key (codLastTeam) references lastTeam(pkLastTeam)
);
I think I can solve the issue adding a new atributte codPlayer1 and changing pkLastTeam for codTeam, codPlayer1.
the table would look like this:
create table position(
codPlayer varchar(12),
codTeam varchar(12),
codPlayer1 varchar(12),
position varchar(20),
primary key (codPlayer, codTeam,codPlayer1),
foreign key (codPlayer) references player(codPlayer),
foreign key (codPlayer,codPlayer1) references lastTeam(codTeam,codPlayer)
);

how to make a primary key a foreign key in another table?

These are my tables. I have a problem with the last one (Inscription) it doesn't accept CodeProjet as a foreign key. The error says table (Projet) doesn't have a primary key called CodeProjet but it does! I have used every trick that I know and nothing. I altered the table to add constraint, etc. Still nothing. I always get the same error. Here are the tables:
create database Gestion_Stages_Employe
create table Employe
(
NumEmploye int primary key,
NomEmploye varchar(15),
PrenomEmploye varchar(15),
SexeEmploye varchar(10),
DNaissEmploye date,
FonctionEmploye varchar(20)
)
create table TypeProjet
(
TypeProjet varchar(20) primary key,
libelleProjet varchar(20),
DureeProjet date,
)
create table Projet
(
CodeProjet int,
TypeProjet varchar(20),
DateDebut Date,
DateFin Date,
Constraint Pk_CodeProj primary key (CodeProjet,TypeProjet),
Constraint FK_TypeProj foreign key (TypeProjet) references TypeProjet(TypeProjet),
)
create table Inscription
(
NumEmploye int foreign key references Employe(NumEmploye),
CodeProjet int foreign key references Projet(CodeProjet),
dateiscription Date,
primary key (NumEmploye,CodeProjet),
)
As was mentioned in the comment, the Primary Key on the Projet table is a "composite key" (multiple columns are required to enforce uniqueness).
As a result, for your foreign key to work, you need to either remove "TypeProjet" from the primary key of Project (assuming CodeProjet is sufficient to uniquely identify a Projet), or you need to add TypeProjet to the Inscription table and define your foreign key with both columns, for example:
create table Inscription (
NumEmploye int foreign key references Employe(NumEmploye),
CodeProjet int,
dateiscription Date,
TypeProjet varchar(20),
Constraint fk_Inscription_project Foreign key (CodeProjet,TypeProjet) references Projet(CodeProjet,TypeProjet),
primary key (NumEmploye,CodeProjet),
)

Syntax error User_id not found in table help !

Sql wont let me create these table because of a syntax error can someone help me.
drop table users;
drop table intrest;
drop table friendships;
create table users(
id INT,
Fname char(15),
Lname char(15),
email char(20),
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone INT,
User_password char(15),
primary key (id),
foreign key (intrest_id) references intrest(id)
);
create table Intrests(
id INT,
description char(30),
Primary key (id),
foreign key (users_id) references users(id)
);
create table User_intrest(
foreign key (users_id) references users(id),
foreign key (intrest_id) references intrest(id)
);
create table friendships(
User_1_id INT,
User_2_id INT,
description Char(20),
foreign key (users_id) references users(id)
);
create table Intrests( id INT, description char(30),
Primary key (id),
foreign key (users_id) references users(id) );
create table User_intrest( foreign key (users_id) references users(id),
foreign key (intrest_id) references intrest(id) );
For interests table, where is the column users_id defined?
Column definitions for user_interest table?
You have a cyclical FK relationship:
Users has Interests(id) as a FK, and Interests has user(id) as a FK.
You don't need EITHER of these since you have a user_intrest table to link them!
You also have several typos with table names, like intrests and intrest.
Also, you should make both your User fields in Friendships be FK to Users, I'm not sure why you want a third, unrelated Users_Id field.
The first (of many) syntax errors you have is in
create table users(
...
primary key (id),
foreign key (intrest_id) references intrest(id) <--- there is no table intrest
);
I would suggest:
But STOP! Don't just copy-paste. Try yourself to see why MySQL gives you that error message: Key column 'intrest_id' doesn't exist in table, isn't the error you get?
Try to first fix that error. What do you have to do? Add an intrest_id field in table users, not just declare it as FOREIGN KEY. (It's not a useful field to have in the end, but do it anyway).
Then rerun your query and try to fix next error. One by one. If you realy get stuck somewhere, well, you know a site to ask questions :)
So, try to fix errors one by one, until you have a script that is running without any errors at all. You'll have learned much more than simply copying and pasting any answer.
CREATE TABLE Users(
id INT,
Fname char(15),
Lname char(15),
email char(50), <-- 20 is too small for emails
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone char(20), <-- phone should be char, not INT
user_password char(15),
PRIMARY KEY (id)
); <-- You don't really need a foreign key to Interests,
<-- that's why you have the User_interest "middle" table
CREATE TABLE Interests(
id INT,
description char(30),
PRIMARY KEY (id)
); <-- You don't really need a foreign key to Users,
<-- for the same reasons.
CREATE TABLE User_interest(
user_id INT, <-- These foreign keys are
interest_id INT, <-- good, but you need to
<-- declare them as fields, too
PRIMARY KEY (user_id, interest_id), <-- It's good if all tables have PK
FOREIGN KEY (user_id) REFERENCES Users(id),
FOREIGN KEY (interest_id) REFERENCES Interests(id)
);
CREATE TABLE Friendships(
user_1_id INT,
user_2_id INT,
description char(20),
PRIMARY KEY (user_1_id, user_2_id),
FOREIGN KEY (user_1_id) REFERENCES Users(id),
FOREIGN KEY (user_2_id) REFERENCES Users(id)
);