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.
Related
I have two tables,
diary with columns
id primary key
Narrative text
and
master with columns
id primary key
Diaryid int
EventDate date
Location int
I want to ensure that master(Diaryid) is always a valid diary(id)
Can I use foreign key to achieve this? Bearing in mind that one key is a primary key and the other int.
Any advice would be apprecaited.
Yes you cqan achieve this by using a FOREIGN KEY.
Also you should define it as NOT NULL, so that only exiasting diary keys are allowed
CREATE TABLE master(Diaryid BIGINT NOT NULL
, FOREIGN KEY (Diaryid)
REFERENCES diary(id)
);
You cqan add
ON DELETE CASCADE
So that the Master row will be deleted also when the diary rows gets removed
Don't know what is different but problem is solved.
CREATE TABLE diary(id int AUTO_INCREMENT, Narrative text, PRIMARY KEY(id))
CREATE TABLE master(id int AUTO_INCREMENT, Diaryid int,datemade date, FOREIGN KEY(Diaryid) REFERENCES diary(id), primary key (id))
So am now adding diary records and can have multiple master records so long as the Diaryid is valid
Thanks
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'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 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
Hi this is the table I am trying to create:
CREATE TABLE images
(
id PRIMARY KEY NOT NULL INT,
product_id FOREIGN KEY NOT NULL INT,
src varchar(255) NOT NULL
)
But its not letting me (I am getting a syntax error). Anyone have any ideas?
CREATE TABLE IMAGES(
Id int NOT NULL,
PRODUCT_ID int NOT NULL,
src varchar(255) NOT NULL,
PRIMARY KEY (Id),
FOREIGN KEY (P_Id) REFERENCES PRODUCTS(P_Id)
)
and make sure you build the Products table first , and do the reference foreign key
Check out InnoDB Foreign Key Constraints for the right syntax to use. In particular, you need to declare the column you're referencing when you create a foreign key.
Additionally, since you're using MySQL, make sure your tables use InnoDB, otherwise the foreign keys won't actually get enforced.