Mysql mapping table FK constraints - mysql

I'm experiencing some difficulties with foreign key constraints. I have three tables:
Features
ID PK AUTO_INC
Title VARCHAR
Subscriptions
ID PK AUTO_INC
Title VARCHAR
Subscriptionfeatures
ID PK AUTO_INC
feature_id INT (index)
subscription_id INT (index)
When I have the following records
Features
1 Testfeature
Subscriptions
1 Testsubscription
I can insert the following record in Subscriptionfeatures when defining a FK constraint as follows
ALTER TABLE subscriptionfeatures ADD CONSTRAINT FK_feature FOREIGN KEY (feature_id) REFERENCES features(id);
Subscriptionfeatures
x 1 1 => ok
But I can not insert the identical record when adding an ON DELETE CASCADE clause to the FK constraint, but i must admint i do not understand its reason for denial!
ALTER TABLE subscriptionfeatures ADD CONSTRAINT FK_feature FOREIGN KEY (feature_id) REFERENCES features(id) ON DELETE CASCADE;
Subscriptionfeatures
x 1 1 => fails
Any help on this would be greatly appreciated!

This works for me:
CREATE TABLE Features (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(100)
) Engine=InnoDB;
CREATE TABLE Subsriptions (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(100)
) Engine=InnoDB;
CREATE TABLE Subscriptionfeatures (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
feature_id INT NOT NULL,
subscription_id INT NOT NULL,
KEY ix_subscriptionfeatures_feature (feature_id),
KEY ix_subscriptionfeatures_subscription (subscription_id)
) Engine=InnoDB;
INSERT
INTO Features
VALUES (1, 'Testfeature');
INSERT
INTO Subsriptions
VALUES (1, 'Testsubscription');
ALTER TABLE subscriptionfeatures ADD CONSTRAINT FK_feature FOREIGN KEY (feature_id) REFERENCES features(id) ON DELETE CASCADE;
INSERT
INTO Subscriptionfeatures (feature_id, subscription_id)
VALUES (1, 1);
What is the error the MySQL gives?

Related

How to create a table with a composite key made of 2 foreign keys referencing to other tables?

I have three tables A, B and funding:
Table A has a primary key partner_id
Table B has a primary key branch_id
When I try to create table C with the following code:
CREATE TABLE Funding (
partner_id INT,
branch_id INT,
total_fund FLOAT,
PRIMARY KEY (partners_id, branch_id),
FOREIGN KEY (partners_id) REFERENCES A(partner_id) ON delete SET NULL,
FOREIGN KEY (branch_id) REFERENCES B(branch_id) ON delete SET NULL
);
I get error message:
1830: column partner_id cannot be NOT NULL: needed in a foreign key constraint.
How can I solve this problem?
Create a separted ID for PK:
SQL DEMO
CREATE TABLE A (
partner_id INT,
PRIMARY KEY (partner_id)
);
CREATE TABLE B (
branch_id INT,
PRIMARY KEY (branch_id)
);
CREATE TABLE Funding (
id INT PRIMARY KEY AUTO_INCREMENT,
partner_id INT,
branch_id INT,
total_fund FLOAT,
FOREIGN KEY (partner_id) REFERENCES A(partner_id) ON DELETE SET NULL,
FOREIGN KEY (branch_id) REFERENCES B(branch_id) ON DELETE SET NULL
);
You can also add:
ALTER TABLE `Funding` ADD UNIQUE `unique_index`(partner_id, branch_id);
But that can cause problem when multiple partners from same branch are deleted
In CREATE TABLE Funding just add NOT NULL statement to partner_id and branch_id.
CREATE TABLE Funding ( partner_id INT NOT NULL, branch_id INT NOT NULL,...

How to Link Foreign Key with Different Name

I have 2 different tables: Profile and Transaction
Profile consists of: pID, firstName, lastName, phoneNumb
Transaction consists of: transID, sellerID, buyerID, itemID
My question is:
How to make sure that both sellerID and buyerID act as a foreign key in reference to profileID in Profile table?
My current code right now:
CREATE TABLE PROFILE
(
pID INT NOT NULL AUTO_INCREMENT ,
firstName VARCHAR(20) NOT NULL ,
lastName INT(20) NOT NULL ,
phoneNumb INT NOT NULL ,
PRIMARY KEY (pID)
) ENGINE = InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE TRANSACTION
(
tID INT NOT NULL AUTO_INCREMENT ,
sellerID INT ,
buyerID INT,
itemID INT,
PRIMARY KEY (tID),
FOREIGN KEY (sellerID, buyerID) REFERENCES PROFILE(pID),
FOREIGN KEY (itemID) REFERENCES ITEM (itemID)
) ENGINE = InnoDB DEFAULT CHARSET=latin1;
I tried this and it gave me this kind of error
1239 - Incorrect foreign key definition for 'foreign key without name': Key reference and table reference don't match
Thanks.
I would go about it this way:
CREATE TABLE TRANSACTION
(
tID INT NOT NULL AUTO_INCREMENT,
sellerID INT,
buyerID INT,
itemID INT,
PRIMARY KEY (tID),
CONSTRAINT fk1 FOREIGN KEY (sellerID) REFERENCES PROFILE(pID)
CONSTRAINT fk2 FOREIGN KEY (buyerID) REFERENCES PROFILE(pID)
CONSTRAINT itemKey FOREIGN KEY (itemID) REFERENCES ITEM (itemID)
) ENGINE = InnoDB DEFAULT CHARSET=latin1;
This assumes that a table called ITEM exists which has a primary key called itemID. Your original problem mentioned only two tables. If ITEM does not exist, then either create it or remove the foreign key constraint from TRANSACTION.

Foreign Key After Table Creation

I have already created a table in MySQL! And have tried a number of queries to alter the table and add foreign key to the table!
But none of them work??
No error message no nothing but still nothing happening...
I need the exact query which would work! :(
Details:
Table1: users column: id
Table2: Pokemon_ref column: pkmn_id
If an insertion is done in Table1 then it should also be added in Table2!
sample:
ALTER TABLE tablename
ADD CONSTRAINT FK_Name_ID FOREIGN KEY (fk_ID)
REFERENCES (R_id);
https://dev.mysql.com/doc/refman/5.1/en/create-table-foreign-keys.html
http://www.w3schools.com/sql/sql_foreignkey.asp
Alter table to give foreign key constraint
category INT NOT NULL, id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)
) ENGINE=INNODB;
CREATE TABLE customer (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE product_order (
no INT NOT NULL AUTO_INCREMENT,
product_category INT NOT NULL,
product_id INT NOT NULL,
customer_id INT NOT NULL,
PRIMARY KEY(no),
INDEX (product_category, product_id),
INDEX (customer_id),
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (customer_id)
REFERENCES customer(id)
)

Allow a foreign key insertion only if another foreign key is matched

I have these 3 tables:
--company--
company_id (primary key)
name
--location--
location_id (primary key)
company_id (foreign key referencing company.company_id)
name
--asset--
asset_id (primary_key)
company_id (foreign key referencing company.company_id)
location_id (foreign key referencing location.location_id)
name
I would like to enforce this: a location_id for an asset is acceptable only if asset.company_id = location.company_id
currently I'm enforcing this through the application, I was wondering if it's possible to do this using only MySQL.
drop table company;
create table company
( company_id int not null auto_increment,
name varchar(100) not null,
primary key(company_id)
)ENGINE=InnoDB
;
insert into company(name) values ('acme widgets');
insert into company(name) values ('goober chocolates');
insert into company(name) values ('Fat R Us');
drop table location;
create table location
( location_id int not null,
company_id int not null,
name varchar(100) not null,
primary key(company_id,location_id),
FOREIGN KEY (company_id ) REFERENCES company(company_id)
)ENGINE=InnoDB
;
insert into location(location_id,company_id,name) values (1,1,'Cambridge MA');
insert into location(location_id,company_id,name) values (1,2,'Boston MA');
insert into location(location_id,company_id,name) values (1,3,'Topeka KS');
insert into location(location_id,company_id,name) values (2,1,'Everywhere USA');
insert into location(location_id,company_id,name) values (2,666,'Fail Test this will fail');
create table asset
( asset_id int not null auto_increment,
company_id int not null,
location_id int not null,
name varchar(100) not null,
primary key(asset_id),
CONSTRAINT fk_asset_cl FOREIGN KEY (company_id,location_id)
REFERENCES location(company_id,location_id)
)ENGINE=InnoDB
;
insert into asset(company_id,location_id,name) values (1,1,'typewriter');
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');
remember that your FK must be back to a single parent table with a key in the same composite order (company,location) in this example
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ...

Adding foreign key on multiple columns

I'm trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error...
Here's what I do:
CREATE TABLE test2 (
ID INT NOT NULL AUTO_INCREMENT,
col1 INT NOT NULL,
col2 INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk FOREIGN KEY (col1, col2)
REFERENCES test1(ID, ID)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB;
But I get
ERROR 1005 (HY000): Can't create table 'DB.test2' (errno: 150)
If I only have one column, however, the table is correctly created.
Could someone point out to me where the error is?
Thanks
n
Tried it here and got the same error. This works though:
CREATE TABLE test2 (
ID INT NOT NULL AUTO_INCREMENT,
col1 INT NOT NULL,
col2 INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk FOREIGN KEY (col1)
REFERENCES test1(ID)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk2 FOREIGN KEY (col2)
REFERENCES test1(ID)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB
Yes, I know - your script should work (even if it doesn't seem to make much sense). Yet, I guess this new version is better.
The problem would appear to be that you are specifying the same parent column twice in the same foreign key (i.e, (ID, ID)). The following should work:
Create Table Test1
(
PK1 int not null
, PK2 int not null
, Primary Key ( PK1, PK2 )
)
Create Table Test2
(
Id int not null Auto_Increment
, PK1 int not null
, PK2 int not null
, Primary Key ( ID )
, Constraint FK_Test2
Foreign Key ( PK1, PK2 )
References Test1( PK1, PK2 )
)
If it is the case, that you want two columns in a child table referencing the same parent table column, then you must add two foreign key references as shown by rsenna as those represent two independent relations.