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

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.

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.

Can't add my second Foreign Key Constraint

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.

Unable to alter table with foreign key

My two empty tables:
CREATE TABLE person (
person_id SMALLINT UNSIGNED,
fname VARCHAR(20),
lname VARCHAR(20),
gender ENUM('m', 'f'),
birth_date DATE,
street VARCHAR(30),
city VARCHAR(20),
state VARCHAR(20),
country VARCHAR(20),
postal_code VARCHAR(20),
CONSTRAINT pk_person PRIMARY KEY (person_id)
);
create TABLE favorite_food (
person_id SMALLINT UNSIGNED,
food VARCHAR(20),
CONSTRAINT pk_favorite_food PRIMARY KEY (person_id, food),
CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id) REFERENCES person (person_id)
);
Needed modification:
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
Result:
ERROR 1833 (HY000): Cannot change column 'person_id': used in a
foreign key constraint 'fk_fav_food_person_id' of table
'tom.favorite_food'
Why is this and is there a way around this without dropping the tables and redefining them?
This is probably because there already is data in person.person_id in any rows (NOT NULL). You can circumvent this by disabling foreign key checks
I believe the best way to handle this is to drop the foreign key reference from favorite_food, alter the column in person and then recreate the foreign key reference. That will properly recreate the index on which the key depends.

What am I doing wrong in this mySQL foreign key set up?

SOLVED! Answered in separate post below
"Cannot add foreign key constraint"
This occurs ONLY when in table Consist_of I use the code:
INDEX trade_name (trade_name),
FOREIGN KEY (trade_name)
REFERENCES Drug(trade_name)
ON DELETE CASCADE,
PRIMARY KEY (pre_no, dssn, pname, trade_name)
If I take out trade_name from PRIMARY KEY () and remove the INDEX to CASCADE, code, then my stuff successfully compiles. All I'm trying to do is have it so I can enter in Drugs with the same name, and have the unique key be the combination of pname and trade_name
all code:
CREATE TABLE Doctor (
dssn INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
dname VARCHAR(30),
specialty VARCHAR(30)
);
CREATE TABLE Prescription (
pre_no INT(6) UNSIGNED PRIMARY KEY,
dssn INT(6) UNSIGNED,
INDEX dssn (dssn),
FOREIGN KEY (dssn)
REFERENCES Doctor(dssn)
ON DELETE CASCADE,
pdate DATETIME
);
CREATE Table Ph_company (
pname varchar(30) PRIMARY KEY,
phone varchar(12)
);
CREATE Table Drug (
pname varchar(30),
trade_name VARCHAR(30),
formula VARCHAR(30),
INDEX pname (pname),
FOREIGN KEY (pname)
REFERENCES Ph_company(pname)
ON DELETE CASCADE,
key(pname, trade_name)
);
CREATE Table Consist_of (
pre_no INT(6) UNSIGNED,
dssn INT(6) UNSIGNED,
pname varchar(30),
trade_name VARCHAR(30),
INDEX pre_no (pre_no),
FOREIGN KEY (pre_no)
REFERENCES Prescription(pre_no)
ON DELETE CASCADE,
INDEX dssn (dssn),
FOREIGN KEY (dssn)
REFERENCES Prescription(dssn)
ON DELETE CASCADE,
INDEX pname (pname),
FOREIGN KEY (pname)
REFERENCES Drug(pname)
ON DELETE CASCADE,
INDEX trade_name (trade_name),
FOREIGN KEY (trade_name)
REFERENCES Drug(trade_name)
ON DELETE CASCADE,
PRIMARY KEY (pre_no, dssn, pname, trade_name)
);
Since the primary key in DRUG is a composite key consisting of 2 fields, you must set up the foreign key the same way. So instead of declaring 2 foreign keys (1 for pname and another for trade_name), do this instead:
FOREIGN KEY ('pname','trade_name')
REFERENCES Drug('pname','trade_name')
Figures that after 2 hours of head-banging, I figure out the solution (I think) 2 minutes after I ask you guys here.
I added
INDEX trade_name (trade_name),
key(pname, trade_name)
to the end of Drug's creation code, and it works now, allowing me to enter in duplicate drug names.

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