mysql foreign key to compound primary key [duplicate] - mysql

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.

Related

How to add constraint to a colum in MYSQL only to hold values which are already present in another column of same table? [duplicate]

This question already has answers here:
Add Foreign Key to existing table
(16 answers)
Closed 2 years ago.
This is the table that I am supposed to create:
Table
In Manager_ID column I am supposed to add a constraint but I am not sure how to do It
This is my code:
CREATE TABLE CANDIDATE
(
Candidate_ID FLOAT(6) PRIMARY KEY,
Candidate_Name VARCHAR(20) NOT NULL,
Candidate_Email VARCHAR(30) UNIQUE,
Candidate_Dept CHAR(2) DEFAULT 'HR',
Manager_ID VARCHAR(30),
CONSTRAINT CHECK (Candidate_Email LIKE '%#%.%'),
CONSTRAINT CHECK (Manager_ID IN (SELECT DISTINCT Candidate_ID FROM CANDIDATE))
);
Can someone help me to add necessary statment to achive above given task.
You are confusing CHECK constraints with FOREIGN KEY constraints. Your second constraint should be a foreign key:
CREATE TABLE CANDIDATE (
Candidate_ID FLOAT(6) PRIMARY KEY,
Candidate_Name VARCHAR(20) NOT NULL,
Candidate_Email VARCHAR(30) UNIQUE,
Candidate_Dept FLOAT(2) DEFAULT 'HR',
Manager_ID VARCHAR(30),
CONSTRAINT CHECK (Candidate_Email LIKE '%#%.%'),
CONSTRAINT fk_candidate_manager_id FOREIGN KEY (Manager_ID) REFERENCES CANDIDATE(Candidate_ID)
);
I don't understand this definition:
Candidate_Dept FLOAT(2) DEFAULT 'HR',
'HR' is not a valid floating point value. Presumably, you intend a string for that column. And you should never use floating point values for primary keys!
Here is an actually working create table statement that is reasonable:
CREATE TABLE CANDIDATE (
Candidate_ID INT PRIMARY KEY,
Candidate_Name VARCHAR(20) NOT NULL,
Candidate_Email VARCHAR(30) UNIQUE,
Candidate_Dept VARCHAR(20) DEFAULT 'HR',
Manager_ID INT,
CONSTRAINT CHECK (Candidate_Email LIKE '%#%.%'),
CONSTRAINT fk_candidate_manager_id FOREIGN KEY (Manager_ID) REFERENCES CANDIDATE(Candidate_ID)
);
Not a check, but foreign key constraint.
I don't know MySQL syntax; in Oracle, that would be
constraint fk_mgr_cand foreign key (manager_id) references candidate (candidate_id)
I hope you can apply something similar to MySQL.

Using same FK in mutliple tables.

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.

SQL table with multiple foriegn keys

I'm trying to make a table with multiple keys
CREATE TABLE Wishlist (ID integer NOT NULL, productname varchar(30) NOT NULL, price integer NOT NULL, email varchar(30) NOT NULL,
PRIMARY KEY (ID),
FOREIGN KEY (productname) REFERENCES products (productname),
FOREIGN KEY (price) REFERENCES products (price),
FOREIGN KEY (email) REFERENCES products (email)
);
The error "a UNIQUE constraint does not exist on referenced columns repeats code" If i change it to:
CREATE TABLE Wishlist (ID integer UNIQUE NOT NULL, productname varchar(30) NOT NULL, price integer NOT NULL, email varchar(30) NOT NULL, // rest same as above
The error "a UNIQUE constraints already exists on the set of columns in statement repeats code" if i then remove the primary key, the first error message appears, any suggestions??
Foreign keys can only be configured on columns in the foreign table that are indexed. Make sure the columns in the foreign tables have an indexed configured. Typically, most foreign keys are configured to the tables PK but non-clustered index work also.

MySQL error for 2 tables cannot add foreign key constraint

I am trying to create 2 tables in the same database. however it still cannot create foreign key.
create table countryadrc
(
adrc char(3) not null,
county varchar(30) not null,
primary key (adrc),
unique (adrc, county)
);
it is the other table which observe the error
create table localities
(
county varchar(30) not null,
locality tinyint not null,
primary key (county),
foreign key (county) references countryadrc (county)
);
Your schema seems to be a little strange but you can technically make it work if you swap columns in UNIQUE constraint in countryadrc table.
Using FOREIGN KEY Constraints
... In the referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order ...
create table countryadrc
(
adrc char(3) not null,
county varchar(30) not null,
primary key (adrc),
unique (county, adrc) -- county should be the leftmost column in the index
);
Here is SQLFiddle demo

Can a table have two foreign keys?

I have the following tables (Primary key in bold. Foreign key in Italic)
Customer table
ID---Name---Balance---Account_Name---Account_Type
Account Category table
Account_Type----Balance
Customer Detail table
Account_Name---First_Name----Last_Name---Address
Can I have two foreign keys in the Customer table and how can I implement this in MySQL?
Updated
I am developing a web based accounting system for a final project.
Account Category
Account Type--------------Balance
Assets
Liabilities
Equity
Expenses
Income
Asset
Asset_ID-----Asset Name----Balance----Account Type
Receivable
Receivable_ID-----Receivable Name-------Address--------Tel-----Asset_ID----Account Type
Receivable Account
Transaction_ID----Description----Amount---
Balance----Receivable_ID----Asset_ID---Account Type
I drew the ER(Entity relationship) diagram using a software and when I specify the relationship it automatically added the multiple foreign keys as shown above. Is the design not sound enough?
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
Yes, MySQL allows this. You can have multiple foreign keys on the same table.
Get more details here FOREIGN KEY Constraints
The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.
There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.
Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.
CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage LONGBLOB NOT NULL,
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);
and
CREATE TABLE Event (
EventID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (EventID),
EventName VARCHAR(100) NOT NULL,
EventLocation VARCHAR(100) NOT NULL,
EventPriceRange VARCHAR(100) NOT NULL,
EventDate Date NOT NULL,
EventTime Time NOT NULL,
EventDescription VARCHAR(255) NOT NULL,
EventCategory VARCHAR(255) NOT NULL,
EventImage LONGBLOB NOT NULL,
index(EventID),
FOREIGN KEY (EventID) REFERENCES User(user_id)
);