MySQL : how to add foreign key - mysql

I have the following code in mysql.
create table employee(
e_id int(10) not null auto_increment,
user_id int(10),
usertype_id default 1,
name varchar(50),
primary key (e_id)
);
create table relation(
r_id int(10) not null auto_increment,
user_id int(10) not null,
usertype_id int(10) not null,
interest_id int(10) not null,
primary key (id)
);
Firstly, i want user_id will have the same value as column e_id;
And then, i want to add user_id and usertype_id as an unity in table relation as a foreign key for user_id and usertype_id in table employee.
Do you know how to do that?
Thanks a lot.

You can make user_id and usertype_id in table relation as foreign keys for the same columns in table employee like this:
create table relation(
r_id int(10) not null auto_increment,
foreign key user_id references employee(user_id),
foreign key usertype_id references employee(usertype_id),
interest_id int(10) not null,
primary key (id)
);
I can't help you with e_id and user_id being equal to each other. Honestly, it sounds like a waste of space.

You could introduce a trigger to guarantee that e_id and user_id contain the same value, but I agree with the previous poster. What's the point?

Related

errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps

sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:
Table users
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
cname varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
Table behaviours
CREATE TABLE behaviours (
id int(2) AUTO_INCREMENT PRIMARY KEY,
bName varchar(100) NOT NULL
);
Table severytys
CREATE TABLE severitys (
id int(2) AUTO_INCREMENT PRIMARY KEY,
severity varchar(10) NOT NULL
);
And here it shows errors:
CREATE TABLE child_behaviours(
id int(11) primary key auto_increment,
name varchar(50) not null,
cname varchar(50) not null,
bName varchar(100) NOT NULL,
severity varchar(10) NOT NULL,
start_at datetime,
stop_at datetime null,
FOREIGN KEY (id) REFERENCES users(id),
FOREIGN KEY (bName) REFERENCES behaviours(bName),
FOREIGN KEY (severity) REFERENCES severitys(severity)
);
Will be really pleasent to have an answer to this issue
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.
If you reference anything other than the PK, you need a really really good reason.
(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)
Now, child_behaviours has several errors:
Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.
Reference to behaviors(bName) instead of using its id
same thing for reference to severity
Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:
SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...
You have to refer to a primary key, when building a foreign key
CREATE TABLE child_behaviours(
userId int not null,
behaviourId int NOT NULL,
severityId int NOT NULL,
start_at datetime not null,
stop_at datetime,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
FOREIGN KEY (severityId) REFERENCES severitys(id)
);

Error creating mysql table with Foreign Key

I have researched thoroughly before asking this question including on this site.
I have a students table:
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id),
UNIQUE (email));
I also have a subjects table:
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(40) NOT NULL,
level_of_entry VARCHAR(20) NOT NULL,
exam_board VARCHAR(20) NOT NULL,
PRIMARY KEY (subject_id));
I am now creating a table to link the above tables:
CREATE TABLE IF NOT EXISTS entries(
exam_date DATETIME NOT NULL,
FOREIGN KEY (student_id) REFERENCES students (student_id),
FOREIGN KEY (subject_id) REFERENCES subjects (subject_id)
);
My problem is that when I try to declare the foreign keys in the third table called entries, I get an error stating that the subject_id foreign key is not in the table referenced.
ERROR 1072 (42000) : Key column 'student_id' doesn't exist in table, even though it is clearly contained inside the the students table and the same applies to 'subject_id' and the subject table.
I am certain that my syntax for declaring the foreign keys is correct so I am unsure how to fix the problem.
All help is appreciated. Thank you.
You forgot to create these two columns before applying your foreign key constraints :
CREATE TABLE IF NOT EXISTS entries(
exam_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
student_id INT UNSIGNED NOT NULL,
subject_id INT UNSIGNED NOT NULL,
exam_date DATETIME NOT NULL,
PRIMARY KEY (exam_id),
FOREIGN KEY (student_id) REFERENCES students (student_id),
FOREIGN KEY (subject_id) REFERENCES subjects (subject_id)
);
EDIT :
I advise you to add in every table a unique ID column (here : exam_id).

Creating MySQL relationships with foreign keys and alter statements

I will try to be specific because I feel my understanding of the subject isn't quite precise as well. My problem is understanding how to create relations between tables with foreign keys which I add with alter statements. I have these tables.
CREATE TABLE article (
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL,
);
CREATE TABLE category(
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL,
);
CREATE TABLE user(
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL,
);
CREATE TABLE tag(
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL,
);
To which I have to make there relationships:
Tag has a one to one connection to Category
Category has a many to one connection to User
User has a one to many connection to Article
And to do that I use there statements:
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (tag_id) REFERENCES category (category_id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE user ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES article (user_id);
My problem is that the third one fails. When I switch the places of article and user the constraint passes. After a bit of digging and experimenting I found out that I can't constraint two keys from which one is either UNIQUE or PRIMARY KEY and the other one just NOT NULL. So far I don't know how to continue, can someone please enlighten me as to how to create a one to one, many to one, one to many and a many to many relationship between these tables because I am kinda lost and everything in my head is a mess.
FULL STUFF:
CREATE DATABASE exam_database;
USE exam_database;
CREATE TABLE article (
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL,
user_id INT(30) NOT NULL
);
CREATE TABLE category(
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL,
category_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT(30) NOT NULL
);
CREATE TABLE user(
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL,
user_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE
);
CREATE TABLE tag(
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL,
tag_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE
);
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (tag_id) REFERENCES category (category_id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE user ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES article (user_id);
First Your structure has some errors:
Missing PK, Why using INT(30)? etc...
Your DB should looks like:
CREATE DATABASE exam_database;
USE exam_database;
CREATE TABLE article (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT NOT NULL,
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL
);
CREATE TABLE category(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL
);
CREATE TABLE user (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE ,
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL
);
CREATE TABLE tag (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
category_id INT NOT NULL,
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL
);
Second Your FKs should look like:
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (category_id) REFERENCES category (id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (id);
ALTER TABLE article ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (id);

Mysql Foreign keys error 150

I'm a mysql beginner and I'm currently working on foreign keys.
I would like to create three tables: users, items, orders and link them together
Users table:
CREATE TABLE users (
user_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
PRIMARY KEY(user_id)
);
Items table:
CREATE TABLE items (
item_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
PRIMARY KEY(item_id)
);
Orders table:
CREATE TABLE orders (
order_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
item_id INT,
quantity INT(10) NOT NULL,
user_id INT,
PRIMARY KEY (order_id),
FOREIGN KEY (item_id) REFERENCES items (item_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
But I got the error 1005: can't create table 'new.orders' (error:150)
What is wrong with my code?
Thanks!
The data types of the primary table's column and the referencing table's columns must match exactly. In your definitions, items.item_id is INT UNSIGNED, while the foreign key orders.item_id is INT (implicitly SIGNED). The same is true for user_id.
Change the definition as follows, adding UNSIGNED for those two:
CREATE TABLE orders (
order_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
item_id INT UNSIGNED,
quantity INT(10) NOT NULL,
user_id INT UNSIGNED,
PRIMARY KEY (order_id),
FOREIGN KEY (item_id) REFERENCES items (item_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
It then builds correctly: http://sqlfiddle.com/#!2/cfab8
There is no column student_id in items table. Did you mean user_id in users table?

How can I add a foreign key when creating a new table?

I have these two CREATE TABLE statements:
CREATE TABLE GUEST (
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
);
CREATE TABLE PAYMENT (
id int(15) not null auto_increment
Foreign Key(id) references GUEST(id),
BillNr int(15) not null
);
What is the problem in the second statement? It did not create a new table.
The answer to your question is almost the same as the answer to this one .
You need to specify in the table containing the foreign key the name of the table containing the primary key, and the name of the primary key field (using "references").
This has some code showing how to create foreign keys by themselves, and in CREATE TABLE.
Here's one of the simpler examples from that:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
I will suggest having a unique key for the payment table. On it's side, the foreign key should not be auto_increment as it refer to an already existing key.
CREATE TABLE GUEST(
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
) ENGINE=INNODB;
CREATE TABLE PAYMENT(
id int(15)not null auto_increment,
Guest_id int(15) not null,
INDEX G_id (Guest_id),
Foreign Key(Guest_id) references GUEST(id),
BillNr int(15) not null
) ENGINE=INNODB;
Make sure you're using the InnoDB engine for either the database, or for both tables. From the MySQL Reference:
For storage engines other than InnoDB,
MySQL Server parses the FOREIGN KEY
syntax in CREATE TABLE statements, but
does not use or store it.
create table course(ccode int(2) primary key,course varchar(10));
create table student1(rollno int(5) primary key,name varchar(10),coursecode int(2) not
null,mark1 int(3),mark2 int(3),foreign key(coursecode) references course(ccode));
There should be space between int(15) and not null