Can't add my second Foreign Key Constraint - mysql

CREATE TABLE Transcripts (sID VARCHAR(7), cNo VARCHAR(10),
semester VARCHAR(20), grade CHAR(1), PRIMARY KEY (sID)
);
CREATE TABLE Students (sID CHAR(7), sName VARCHAR(20),
bDate DATE, phone VARCHAR(12), major VARCHAR(30), avgGPA VARCHAR(4), PRIMARY KEY (sID),
FOREIGN KEY (sID)
REFERENCES Transcripts(sID)
);
CREATE TABLE Courses (cNo VARCHAR(10), cTitle VARCHAR(30),
creditHours VARCHAR(2), deptName VARCHAR(30), PRIMARY KEY (cNo),
FOREIGN KEY (cNo)
REFERENCES Transcripts(cNo)
);
So whenever I run this, the first foreign key works just fine, whenever I run the next table it gives me back this error "ERROR 1215 (HY000): Cannot add foreign key constraint" What did I do wrong?

This is the foreign key that produces the error:
FOREIGN KEY (cNo)
REFERENCES Transcripts(cNo)
But the Transcripts(cNo) is not part of any KEY in that table.
A foreign key must reference column(s) of a UNIQUE or PRIMARY KEY of the parent table.
See MySQL Creating tables with Foreign Keys giving errno: 150 for a good checklist required for a foreign key.

Index the foreign key column before adding the foreign key.
CREATE TABLE Courses (cNo VARCHAR(10), cTitle VARCHAR(30),
creditHours VARCHAR(2), deptName VARCHAR(30), PRIMARY KEY (cNo),
INDEX (cNo),
FOREIGN KEY (cNo)
REFERENCES Transcripts(cNo)
);

to define cNo as a foreign key on Courses table, it must be primary key
or a unique key of other table.
CREATE TABLE Transcripts(
sID VARCHAR(7),
cNo VARCHAR(10) NOT NULL UNIQUE,
semester VARCHAR(20),
grade CHAR(1),
PRIMARY KEY (sID)
);
http://sqlfiddle.com/#!9/fddf8
changing Transcripts, as I've written above wil solve your problem.

Isn't the logic backwards? Shouldn't `Transcripts have two FKs referencing the other two tables? And, as already pointed out, declare the other two tables first.

Related

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

CREATE DATABASE employeeDB;
USE employeeDB;
CREATE TABLE employees(
employeeid NUMERIC(9),
firstname VARCHAR(10),
lastname VARCHAR(20),
deptCode CHAR(5),
salary NUMERIC(9, 2),
PRIMARY KEY (employeeid)
);
CREATE TABLE projects(
projectid CHAR(8),
deptcode CHAR(5),
description VARCHAR(200),
startdate DATE,
stopdate DATE,
revenue NUMERIC(12, 2),
PRIMARY KEY (projectid),
FOREIGN KEY (deptcode) REFERENCES employees(deptCode)
);
CREATE TABLE departments(
code CHAR(5),
name VARCHAR(5),
managerid NUMERIC(9),
subdeptof CHAR(5),
PRIMARY KEY (code),
FOREIGN KEY (managerid) REFERENCES employees(employeeid),
FOREIGN KEY (subdeptof) REFERENCES projects(deptcode)
);
ALTER TABLE employees ADD FOREIGN KEY (deptCode) REFERENCES projects(deptcode);
Something wrong at the line CREATE TABLE projects(...). When I run the code in MySQL it give the Error Code 1822. What is the problem ? Any expert can help ?
You cant create foreign key with a non-primary key, and if you really want to create foreign key to non-primary key (column), the column must be indexed with a unique constraint on it.
So either create unique constraint on deptCode column, or reference by already existing primary key, or change the primary key.

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)
);

Why can't I add a foreign key constraint on this?

CREATE TABLE usertypes (
userType INTEGER,
userName VARCHAR(12),
PRIMARY KEY(userType)
);
CREATE TABLE Users (
loginid CHAR(9),
name VARCHAR(15),
netid VARCHAR(15) NOT NULL,
password VARCHAR(15) NOT NULL,
userType INTEGER,
PRIMARY KEY (loginid),
UNIQUE (netid),
FOREIGN KEY (userType) REFERENCES usertypes(userType)
ON DELETE NO ACTION
);
CREATE TABLE Courses (
majorid CHAR(3),
cid CHAR (3),
secNum CHAR(2),
year CHAR(4),
semesterid CHAR(2),
profID CHAR(9),
PRIMARY KEY (majorid,cid,secNum,year,semesterid),
FOREIGN KEY (majorid) REFERENCES Majors (majorid),
FOREIGN KEY (profID) REFERENCES Users(loginid)
);
create table transcript(
cid char(3),
grade char(2),
primary key(cid, grade),
foreign key(cid) references courses(cid)
);
I can't add a foreign key cid in transcript. The foreign key for majorid in courses works fine but the one in transcript doesn't work.
Here's the error
Error Code: 1215. Cannot add foreign key constraint
Course.cid is not a key, so transcript cannot create a foreign key. Try the following:
CREATE TABLE Courses (
majorid CHAR(3),
cid CHAR (3),
secNum CHAR(2),
year CHAR(4),
semesterid CHAR(2),
profID CHAR(9),
PRIMARY KEY (majorid,cid,secNum,year,semesterid),
KEY (cid)
);
Short version is I don't think you can have a foreign key to something that isn't identified as a primary key or something with a unique constraint, see Foreign Key to non-primary key
I'm not sure how you are using the cid in the Courses table, if it is perhaps 110 and there is a Math 110 and a Physics 110. This has the problem of if someone has 110 on their transcript, does it reference Math or Physics?
If cid is a primary key, a unique value for each class, it should be a primary key all by itself. If you are in the situation of 110 for math and physics, you might be best served by adding a primary key that is unique for every row, such as an identity, auto incrementing key.

ERROR 1005 (HY000): Can't create table 'Item_Copy' (errno: 150) unable to create table Item_Copy

I cannot create the table Item_Copy
CREATE TABLE Library
(
Library_ID int primary key,
Library_Address varchar(40),
Library_Phone bigint
);
CREATE TABLE Branch
(
Library_ID int,
Branch_Number int,
Branch_Name varchar(40),
Branch_Address varchar(40),
Branch_Phone bigint,
Branch_Hours varchar(40),
primary key (Library_ID,Branch_Number),
foreign key (Library_ID) references Library(Library_ID)
);
CREATE TABLE Item_Copy
(
Item_ID int primary key,
Copy_Number int,
Copy_Condition varchar(40),
Copy_Date_Acquired date,
Copy_Cost int,
Library_ID int,
Branch_Number int,
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
foreign key (Item_ID) references Item(Item_ID)
);
Just a scientific guess (will drop if it's wrong) (is based on an assumption that Item_ID definitions match):
You wanted a compound foreign key, not 2 separated FKs:
foreign key (Library_ID, Branch_Number) references Branch(Library_ID, Branch_Number)
To define a child relation, parent column must have indexed.
In the parent table Branch, Key is defined as composite.
primary key (Library_ID,Branch_Number),
But, in the child table Item_Copy, you are trying to define reference keys independent on each column.
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
This is only acceptable when each of these fields are referring to respective parent keys.
But Branch(Branch_Number) has no key defined in Branch table. And hence is the error.
Change:
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
To:
foreign key (Library_ID, Branch_Number)
references Branch(Library_ID, Branch_Number),

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)
);