Unable to alter table with foreign key - mysql

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.

Related

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.

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

MySQL - complete newbie - what's wrong with my foreign key coding?

When trying to create the foreign keys on the last table I get the error "cannot add foreign key constraint" -
create database library_PW;
use library_PW;
create table title(
title_id varchar(20)primary key,
name varchar(50)not null,
reservation_no numeric(10),
lending_time varchar(15));
create table item(
title_id varchar(20)not null,
item_id varchar(20)not null,
constraint pk_item primary key(title_id,item_id));
create table magazine(
mag_id varchar(20)not null,
mag_date varchar(15)not null,
constraint pk_magazine primary key(mag_id,mag_date));
create table book(
ISBN varchar(20)primary key,
date_added date not null);
create table author(
author_id varchar(20)primary key,
author_name varchar(30)not null);
create table book_author(
ISBN varchar(20),
author_id varchar(20),
index (ISBN),
index (author_id),
constraint pk_book_author primary key(ISBN,author_id),
constraint fk_ISBNCode foreign key (ISBN) references book(ISBN),
constraint fk_authorcode foreign key (author_id) references author(author_id));
create table borrower(
membership_id varchar(20)primary key,
name varchar(20)not null,
address varchar(60)not null,
dob date not null,
date_joined date not null,
telephone numeric(12),
email varchar(30));
create table reservation(
title_id varchar(20),
membership_id varchar(20),
reserve_date varchar(20),
index (title_id),
index (membership_id),
constraint pk_reservation primary key(title_id, membership_id,reserve_date),
constraint fk_title foreign key(title_id) references title(title_id),
constraint fk_mem_id foreign key(membership_id) references borrower(membership_id));
create table loan(
title_id varchar(20),
item_id varchar(20),
borrower_date varchar(20),
index (title_id),
index (item_id),
constraint pk_reservation primary key(title_id,item_id,borrower_date),
constraint fk_loantitle foreign key(title_id) references title(title_id),
constraint fk_loanitem foreign key(item_id) references item(item_id));
Thanks in advance!
When I run into this issue, its always because I choose the wrong type data type.. The data type for the child column must match the parent column exactly.
Example: table.key = int & table.child=vchar
For me, its always that! Hope that helps.
Thanks all! It wasn't the data type (for once), it was the problem with the table item as suggested, and SHOW ENGINE INNODB STATUS\G pointed me to the answer.
All that was wrong was in the table item I should have had item_id before title_id.
Thanks again.

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.

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