I have 2 tables:
create table TRASchema.Member (
TRAnum int IDENTITY not null,
name varchar(30) not null,
status int not null,
DOB date not null,
constraint PK_TRAnum primary key (TRAnum)
)
create table RaceSchema.RaceEntry
(bibNumber int IDENTITY not null,
AgeCode nchar(2) not null,
ClubID int not null,
TRAnum int not null,
position int not null,
RaceID int not null,
constraint PK_bibNumber primary key (bibNumber),
constraint FK_AgeCode foreign key (AgeCode) references
TRASchema.AgeCatagoryClass(AgeCode),
constraint FK_ClubID foreign key (ClubID) references TRASchema.Club(ClubID),
)
Now I would like to be able to use the same TRAnum on my Race Entry system but as a FK. When I try to do this I would add this constraint to the RaceEntry Table
constraint FK_TRAnum foreign key (TRAnum) references
TRASchema.Member(TRAnum)
When I do this I am informed that the attribute TRAnum already exists elsewhere in my DB which is correct it does and I want to use it again onthis table as a FK?
Any direction on where I am going wrong would be appreciated.
Thanks
It sounds like you're trying to use the same constraint name FK_TRAnum. You can have multiple tables all with an FK that reference the same table, but each constraint must have a unique name.
Related
I have tried adding a foreign key of type VARCHAR that references another table column with type VARCHAR as well. Both Columns are same type and length, but I keep getting an error: Failed to add the foreign key constraint. Missing index for constraint
The first table below has no problem when being created but the second table is the table to which throws the error: Failed to add the foreign key constraint. Missing index for constraint 'FK_Session_User' in the referenced table 'users'
The column I that I am trying to reference is the UserName Column.
CREATE TABLE Users (
UserID INT NOT NULL AUTO_INCREMENT,
Role_Code VARCHAR(15) NOT NULL,
UserName VARCHAR(40) NOT NULL,
Password TEXT NOT NULL,
CONSTRAINT PK_User PRIMARY KEY (UserID, UserName),
CONSTRAINT FK_User_Roles FOREIGN KEY (Role_Code)
REFERENCES Roles(Role_Code));
CREATE TABLE Auth_Users (
SessionID VARCHAR(96) NOT NULL,
UserName VARCHAR(40) NOT NULL,
Last_Visit TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT PK_AuthUser PRIMARY KEY (SessionID),
CONSTRAINT FK_Session_User FOREIGN KEY (UserName)
REFERENCES Users(UserName)
);
the problem is that UserName is not indexed indexed on Users. You should add an index to it. You can do it like this:
CREATE TABLE Users (
UserID INT NOT NULL AUTO_INCREMENT,
Role_Code VARCHAR(15) NOT NULL,
UserName VARCHAR(40) NOT NULL,
Password TEXT NOT NULL,
INDEX(UserName),
CONSTRAINT PK_User PRIMARY KEY (UserID, UserName),
CONSTRAINT FK_User_Roles FOREIGN KEY (Role_Code)
REFERENCES Roles(Role_Code)
);
UPDATE: With that said, please see this: https://stackoverflow.com/questions/588741/can-a-foreign-key-reference-a-non-unique-index#:~:text=From%20MySQL%20documentation%3A,unique%20columns%20of%20referenced%20table.
On why you shouldn't do that.
I would recommend normalizing you data in a way that you have only unique not nulls as your references.
In your case the simplest way to solve it would be to reference UserID in your foreign key. Also, that is what you most probably really want to do.
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
I have created 2 tables with a parent child relationship in MYSQL. However, the foreign key relationship fails with error code 1215. The MAIN_ROLE can have many SUB_ROLE aliases. The SUB_ROLE has a composite PRIMARY key (ID,MAIN_ID,SEQ_NUM). The MAIN_ROLE table's PRIMARY KEY is part of SUB_ROLES primary key.
Here are the tables and my constraints:
create TABLE MAIN_ROLE(
ID int NOT NULL AUTO_INCREMENT,
MAIN_ID int NOT NULL,
ASSIGNED_DATE datetime NULL,
MAIN_ROLE_NM varchar(50) NOT NULL,
PRIMARY KEY(ID,MAIN_ID)
);
create TABLE SUB_ROLE(
ID int NOT NULL,
MAIN_ID int NOT NULL,
SEQ_NUM decimal(15, 0) NOT NULL,
SUB_ROLE_NM varchar(50) NOT NULL,
PRIMARY KEY(ID,MAIN_ID,SEQ_NUM) ,
CONSTRAINT SUB_ROLE_FK REFERENCES MAIN_ROLE(ID,MAIN_ID,SEQ_NUM)
);
Could someone point out what's wrong with the foreign key in my scripts? Please help!
The main problem is that you are not following mysql's foreign key syntax and that you a referencing a field in the parent table that is not there:
You do not provide a list of fields from the child table
SEQ_NUM field does not exist in the main table, only in the sub table.
Correct foreign key definition would look like as follows:
CONSTRAINT SUB_ROLE_FK FOREIGN KEY (ID,MAIN_ID) REFERENCES MAIN_ROLE(ID,MAIN_ID)
However, I do not really see ehat's the point of having an auto increment id field and a main_id field in the main table. I would take a 2nd look at that.
This worked, CONSTRAINT SUB_ROLE_FK FOREIGN KEY (ID,MAIN_ID) REFERENCES MAIN_ROLE(ID,MAIN_ID)
This question already has answers here:
Composite key as foreign key (sql)
(2 answers)
Closed 6 years ago.
I try to achive the following using MySQL Server 5.x.
I have a table named Customer created like this:
CREATE TABLE Customer(
Title VARCHAR(30) NOT NULL,
Name VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
Street VARCHAR(300) NOT NULL,
HouseNumber VARCHAR(30) NOT NULL,
ZipCode VARCHAR(30) NOT NULL,
City VARCHAR(100) NOT NULL,
Telephone VARCHAR(30) NOT NULL,
EMail VARCHAR(300) NULL,
CONSTRAINT PK_Customer PRIMARY KEY(Title,Name,FirstName),
INDEX Index_Name(Name));
And a second table Named 'Order' created like this:
CREATE TABLE `Order`(
Number BIGINT NOT NULL AUTO_INCREMENT,
Customer VARCHAR(230) NOT NULL,
Issued DATETIME NOT NULL,
PRIMARY KEY(Number),
CONSTRAINT FK_Customer FOREIGN KEY(Customer)
REFERENCES Customer(PK_Customer));
But I get an error with the number:
ERROR 1005 (HY000): Can't create table 'SBZ.Order' (errno: 150)
The innodb engine status shows me this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
160317 16:05:29 Error in foreign key constraint of table SBZ/Order:
FOREIGN KEY(Customer) REFERENCES Customer(PK_Customer)):
Cannot resolve column name close to:
))
Is it possible to create a foreign key to a compound primary key using constraint?
Any help appriciated. :)
First, you should have a CustomerId column in the first table. It should be auto-incremented. So the right definitions are:
CREATE TABLE Customer (
CustomerId int auto_increment primary key,
. . .
unique (title, firstname, name)
);
Then you can create a correct foreign key relationship to CustomerId:
CustomerId int,
. . .
CONSTRAINT FK_Customer FOREIGN KEY(CustomerId) REFERENCES Customer(CustomerId)
This is "right" because such synthetic keys have several advantages:
Foreign key references are much simpler.
You can change the components easily (changing part of a foreign key requires understanding cascading constraints).
Integers in indexes are more efficient than strings.
Of course, you can do the same with a composite primary key. You just need all three columns in the second table:
Title VARCHAR(30),
Name VARCHAR(100),
FirstName VARCHAR(100),
CONSTRAINT FK_Customer FOREIGN KEY(Title, Name, Firstname) REFERENCES Customer(Title, Name, Firstname)
Your child table's foreign key must contain the same columns, in the same order, as the primary key of the parent table. In your case it would look like
CREATE TABLE `Order`(
Number BIGINT NOT NULL AUTO_INCREMENT,
Title VARCHAR(30) NOT NULL,
Name VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
...
CONSTRAINT FK_Customer FOREIGN KEY (Title, Name, FirstName)
REFERENCES Customer (Title, Name, FirstName)
);
Note the columns don't have to be in the same order in the table, just in the constraint's column list.
I am stuck with this error no 150 problem in mysql and I know there have been questions
which discuss this problem but I still can't find where I am wrong. Here is the database I am trying to create:
create table business (
ident varchar(40) NOT NULL,
name varchar(50) NOT NULL,
rating INT UNSIGNED NOT NULL,
PRIMARY KEY(ident)
) ENGINE=InnoDB;
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE
) ENGINE=InnoDB;
create table d_options (
business_id varchar(40) NOT NULL,
dealid varchar(20) NOT NULL,
option_title varchar(40) NOT NULL,
PRIMARY KEY(business_id, dealid, option_title),
FOREIGN KEY(business_id) REFERENCES business(ident) ON DELETE CASCADE,
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) ENGINE=InnoDB;
I get error: ERROR 1005 (HY000): Can't create table 'test.d_options' (errno: 150)
I know for foreign key constraints to be satisfied there should be a index in the parent table as per mysql documentation, but I think that there is by default indexing
on primary key.
The result of innodb status is:
120530 0:47:48 Error in foreign key constraint of table test/d_options:
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Any help is appriciated.
You have a compound primary key on (business_id, deal_id) and they are indexed as a pair, but to satisfy the FK, you need another index on deal_id alone:
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE,
/* Add an index on deals_id, separate from the compound PK */
INDEX idx_deals_id (deals_id)
) ENGINE=InnoDB;