I am unable to create these tables in MySQL. Everything looks complete to me but I keep getting errors.
Here is my SQL:
CREATE TABLE Movies(
title char PRIMARY KEY NOT NULL,
Years date NOT NULL,
length decimal not null,
genre char NOT NULL,
academy_award char not null,
FOREIGN KEY(the_name) REFERENCES Studio,
FOREIGN KEY(directorName) REFERENCES Director);
CREATE TABLE StarsIn(
FOREIGN KEY(title) REFERENCES Movies,
FOREIGN KEY(Years) REFERENCES Movies,
FOREIGN KEY(the_name) REFERENCES MovieStar);
CREATE TABLE Director(
the_name char PRIMARY KEY NOT NULL,
birthdate date NOT NULL,
nationality char NOT NULL);
CREATE TABLE MovieStar(
the_name char PRIMARY KEY NOT NULL,
birthdate date NOT NULL,
address char NOT NULL,
gender char NOT NULL);
CREATE TABLE Studio(
the_name char PRIMARY KEY NOT NULL,
address char NOT NULL);
This isn't working because your tables are not being created in the proper order.
The parent table must always be created first, because otherwise you will be trying to reference a column that does not exist.
For example, look at this part here:
CREATE TABLE Movies(title char PRIMARY KEY NOT NULL, Years date NOT NULL,
length decimal not null, genre char NOT NULL, academy_award char not null,
FOREIGN KEY(the_name) REFERENCES Studio, FOREIGN KEY(directorName) REFERENCES Director);
You can't reference tables studio or director because they don't even exist.
The proper order could be:
Studio
Movie Star
Director
Movies
StarsIn
In addition, you have a lot of other problems going on here.
You do not define any columns in the Stars IN table, you only declare foreign keys:
CREATE TABLE StarsIn(
FOREIGN KEY(title) REFERENCES Movies,
FOREIGN KEY(Years) REFERENCES Movies,
FOREIGN KEY(the_name) REFERENCES MovieStar);
Not only are you not defining any columns, you aren't referencing anything. This will also throw an error. Your foreign key title must reference some column in the movies table. And in addition to that, you can't create a foreign key reference for Years. Mostly because you cannot create a foreign key to a column that is not primary key in another table, and also why should you need two foreign keys to the same table?
Those problems exist in other create table statements as well, so given everything I've said please go back and look at each of your create table statements.
Here is a working SQL Fiddle you can use for reference though.
EDIT
I would like to also add that I do not recommend using the char datatype. Please look into using VARCHAR().
The problem you are having is that you are referencing columns in tables that do not exist.
Although you create these tables later, the DBMS engine does not know they will exist.
The solution - create the tables without the FK's that do not exist, and add these later using the "ALTER TABLE" command.
It seems like you know the syntax, so I'll let you inform me if you cannot find it.
your syntax should look like (All I did is re-order, and change char to be archer...):
CREATE TABLE Studio(the_name varchar(50) PRIMARY KEY NOT NULL, address varchar(50) NOT NULL);
CREATE TABLE Director(the_name varchar(50) PRIMARY KEY NOT NULL, birthdate date NOT NULL, nationality varchar(50) NOT NULL);
CREATE TABLE Movies(title varchar(50) PRIMARY KEY NOT NULL, Years date NOT NULL,
length decimal not null, genre varchar(50) NOT NULL, academy_award varchar(50) not null,
the_name REFERENCES Studio(the_name), directorname REFERENCES Director(the_name));
CREATE TABLE MovieStar(the_name char PRIMARY KEY NOT NULL, birthdate date NOT NULL, address char NOT NULL, gender char NOT NULL);
CREATE TABLE StarsIn(title REFERENCES Movies(title),movie REFERENCES Movies(title), moviestar REFERENCES MovieStar(the_name));
A little note, depends on the version - you'd might have to use the FOREIGN KEY(col_name) instead of col_name. I like more the syntax without it, but some versions force you to use FOREIGN KEY(title) instead of title in the last SQL for example.
The syntax you used - Foreign key NAME References TABLE (Column) -- you forgot the column-- Allows you to name the FK. If you don't use the "Foreign Key" the system will randomly assign a name. This is usually not important, unless you want the DB design to be "clean" and to be able to reference it by name.
P.S. - I did not run it, I trust you to inform if there's any other issue - I did not check the syntax, just fixed the error you reported- references that do not exist...
P.S. P.S. Always check syntax... http://dev.mysql.com/doc/refman/5.1/en/create-table.html
Related
Got an odd problem I cant solve after browsing dozens of forum posts, and my local SQL Books.
I've got two tables, and want to add a foreign key to one of them. The foreign key and primary key share the same datatype and charset and yet I cannot add the Foreign Key at all.
addon_account
name
type
comments
id
int(11)
Primary Key
name
varchar(60)
Primary Key
label
varchar(255)
shared
int(11)
addon_account_data
name
type
comments
id
int(11)
Primary Key
account_name
varchar(60)
Primary Key
money
double
owner
varchar()
The query I ran:
ALTER TABLE `addon_account_data` ADD FOREIGN KEY (`account_name`) REFERENCES `addon_account`(`name`) ON DELETE RESTRICT ON UPDATE RESTRICT;
Can't get it to work. Tosses out the same issue the entire time.
You are creating a foreign key on addon_account_data(account_name) that references addon_account(name). You have a composite primary the referred table : addon_account(id, name).
This is not allowed in MySQL, as explained in 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.
Possible solutions:
add an additional column in the referring table: addon_account_data(account_id, account_name) and create a composite primary key to the corresponding columns in addon_account
create an index on addon_account(name) (probably the simplest solution)
change the order of the columns in the primary key of the referred table, like: addon_account(name, id) (you might want to first consider the impacts this may have in terms of performance)
I am not exactly a MySQL guy, but:
I believe the problem is that you are referencing only part of the primary key:
Your table addon_account has a composite key PK(id, name).
So, to put your relationship to work, you will need to add 'account_id' as part of the foreign key as well:
ALTER TABLE addon_account_data ADD FOREIGN KEY (account_id, account_name) REFERENCES addon_account(id, name)
This thread deals with something similar.
I hope this helps.
EDITED
I have installed a MySQL server instance on my local machine... (MySQL 8).
I have run the script below, and it worked (giving warnings about integer display being a deprecated feature, so I would recommend ommitting it):
CREATE TABLE addon_account(
id INT(11) NOT NULL,
`name` VARCHAR(60) NOT NULL,
label VARCHAR(255),
shared INT(11),
CONSTRAINT pk_addon_account PRIMARY KEY(id, `name`));
CREATE TABLE addon_account_data (
id INT(11) NOT NULL,
account_name VARCHAR(60) NOT NULL,
account_id INT(11),
money DOUBLE,
`owner` VARCHAR(255),
CONSTRAINT pk_addon_account_data PRIMARY KEY(id, account_name),
CONSTRAINT fk_addon_account_account_data FOREIGN KEY(account_id, account_name)
REFERENCES addon_account(id, `name`));
Could you try it and see if this works for you?
I am not that familiar with MySQL.
make sure that the 2 tables have the same collation
like
COLLATE='utf8_general_ci'
I am developing a patch version which is by create or update existing table by using raw sql.When I ran these 3 queries like below
first query Success
CREATE TABLE ts_overtime_scheme_histories( id int AUTO_INCREMENT NOT NULL,
name VARCHAR(255),
workdays INT,
break_payable VARCHAR(25),
roundable VARCHAR(25),
round_rule VARCHAR(10), round_minute INT,
type enum('ratio','fixed') DEFAULT 'ratio',
overtime_request_id INT UNSIGNED NOT NULL, PRIMARY KEY(id),
FOREIGN KEY(overtime_request_id) REFERENCES ts_overtime_requests(id) );
Second query success
CREATE TABLE ts_overtime_scheme_details_histories( id INT AUTO_INCREMENT NOT NULL,
hour FLOAT,
ratio FLOAT,
overtime_scheme_history_id INT(11) UNSIGNED NOT NULL,
PRIMARY KEY(id));
And now I am trying to connect second table to the first table. So the first table has foreign key on the second table. So I ran the third query
ALTER TABLE ts_overtime_scheme_details_histories ADD FOREIGN KEY (`overtime_scheme_history_id`) REFERENCES `ts_overtime_scheme_histories` (`id`) ON DELETE CASCADE;
But somehow it failed. The error report is below
General error: 1005 Can't create table `db_test`.`#sql-ea4_28` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: ALTER TABLE ts_overtime_scheme_details_histories
ADD FOREIGN KEY (`overtime_scheme_history_id`) REFERENCES `ts_overtime_scheme_histories` (`id`)
ON DELETE CASCADE;)
Can somebody help me to find what I miss? At first, I suspect the primary and foreign key data length is not similar, but when I double checked, it is correct.
Edit:
table ts_overtime_requests was created using laravel framework.
Column datatype of the foreign key column must match exactly the datatype of referenced key column.
In this case, the reported behavior (Error 1005) is expected because there's a difference in the datatypes of the two columns.
One of the columns is signed integer, the other column is UNSIGNED integer.
Quick fix would be to change the datatype of overtime_scheme_history_id so that is is signed. (Remove the UNSIGNED keyword.)
I'm trying to make a simple SQL schema, but I'm having some problem with defining foreign keys. I really don't have that much MySQL knowledge, so I thought I'd ask her for some help. I get Error Code 1215 when I try to create the foreign key roomID and 'guestEmail' in the HotelManagement.Reservation table creation.
CREATE database HotelManagement;
CREATE TABLE HotelManagement.Room (
roomID INT not null auto_increment,
roomTaken TINYINT(1),
beds INT not null,
size INT not null,
roomRank INT not null,
PRIMARY KEY(roomID));
CREATE TABLE HotelManagement.HotelTask (
taskType INT not null,
taskStatus TINYINT(1) not null,
whichRoom INT not null,
note VARCHAR(255),
PRIMARY KEY (taskType),
FOREIGN KEY (whichRoom) REFERENCES HotelManagement.Room(roomID));
CREATE TABLE HotelManagement.Guest (
firstName varchar(25) not null,
lastName varchar(25) not null,
userPassword varchar(25) not null,
email varchar(25) not null,
reservation INT,
PRIMARY KEY (userPassword, email));
CREATE TABLE HotelManagement.Reservation (
reservationID INT not null,
id_room INT not null,
guestEmail varchar(25) not null,
fromDate DATE not null,
toDate DATE not null,
PRIMARY KEY (reservationID),
FOREIGN KEY (guestEmail)
REFERENCES HotelManagement.Guest(email),
FOREIGN KEY (id_room)
REFERENCES HotelManagement.Room(roomID)
);
ALTER TABLE HotelManagement.Guest
ADD CONSTRAINT res_constr FOREIGN KEY (reservation)
REFERENCES HotelManagement.Reservation(reservationID);
Updated the .sql
In the hoteltask table you have already defined a foreign key named roomid. Foreign key names also have to be unique, so just give a different name to the 2nd foreign key or omit the name completely:
If the CONSTRAINT symbol clause is given, the symbol value, if used,
must be unique in the database. A duplicate symbol will result in an
error similar to: ERROR 1022 (2300): Can't write; duplicate key in
table '#sql- 464_1'. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, a name for the constraint
is created automatically.
UPDATE
The email field in the guest table is the rightmost column of the primary key, this way the pk cannot be used to independently look up email in that table. Either change the order or fields in the pk, or have a separate index on email field in the guest table. Quote from the same link as above:
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. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Pls read through the entire documentation I linked before proceeding with creating the fks!
Side note 2 (1st is in the comments below): you should probably have a unique numeric guest id because that is lot more efficient than using email. Even if you decide to stick with email as id, I would restrict the pk in the guest table to email only. With the current pk I can register with the same email multiple times if I use different password.
I have bulid a new table in my SQL database with the following command :
Create Table if not exists Images (ImageID int (10) primary key NOT NULL AUTO_INCREMENT ,
UserID int (10) NOT NULL,
Translated tinyint Default 0,
DeleteImage tinyint Default 0,
DataPosted date,
TheImage blob,
Translation text,
FOREIGN KEY (UserID) REFERENCES Users(UserID) ON DELETE CASCADE)
the table is been created just fine, but what i'm checking what was build i've found out that in the table the columns ImageID, TheImage, and Translation are defined as primary keys.
as the query is showing I want only the ImageId to be the primary key.
what's happening here?
tnx
Seems quite unlikely. It seems far more likely that something is wrong with whatever tool you're using to find out which columns are primary keys.
Actually, from the documentation - here: http://dev.mysql.com/doc/refman/5.1/en/create-table.html - it would follow that a MySQL table can only have one primary key. But even if not, why would you worry about it?
Hey guys i'm kind of new to the whole world of mysql, the current problem i have is that i can't quite work out why this is not working is it possibly to do with the 2 primary keys? Or is it the references? Thanks in advance
CREATE TABLE IsSeenBy
( PatientCode int (11) NOT NULL,
DoctorCode int (11) NOT NULL,
Date VARCHAR (10) NOT NULL,
Time VARCHAR (5) NOT NULL,
PRIMARY KEY (PatientCode),
PRIMARY KEY (DoctorCode),
PatientCode REFERENCES (Patient),
DoctorCode REFERENCES (Doctor)
;
Date is a reserved word so if you want to name a column that you will need to quote it. Also I'd highly recommend using an actual Date type for that column, not VARCHAR. (unless it needs to be something like a star date.) And yes, you cannot have two primary keys. You need either one or a compound one. Your foreign key definitions do not look correct either
CREATE TABLE IsSeenBy
(PatientCode int (11) NOT NULL,
DoctorCode int (11) NOT NULL,
`Date` DATETIME NOT NULL,
PRIMARY KEY (PatientCode, DoctorCode),
FOREIGN KEY (PatientCode)
REFERENCES Patient(PatientCode)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (DoctorCode)
REFERENCES Doctor(`DoctorCode`)
ON UPDATE CASCADE ON DELETE RESTRICT
);
You can't have 2 PK in the table. If you want composite PK use
PRIMARY KEY (PatientCode, DoctorCode),
instead.
You must explore Foreign key reference documentation too.