Foreign Key After Table Creation - mysql

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)
)

Related

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.

mysql create table not working

I can create any table I want in mysql and it works, except for creating this table:
CREATE TABLE product_shop (
product_id INT NOT NULL,
shop_id INT NOT NULL,
PRIMARY KEY (product_id, shop_id),
FOREIGN KEY (product_id) REFERENCES product(id) ON UPDATE CASCADE,
FOREIGN KEY (shop_id) REFERENCES shop(id) ON UPDATE CASCADE
)
I can create this table and it works:
CREATE TABLE product_category_junction (
product_id INT NOT NULL,
category_id INT NOT NULL,
PRIMARY KEY (product_id, category_id),
FOREIGN KEY (product_id) REFERENCES Product(id) ON UPDATE CASCADE,
FOREIGN KEY (category_id) REFERENCES Category(id) ON UPDATE CASCADE
)
Or any other table. Even if I name the product_shop table to something else it won't create it.
When I try to create it, it says :
#1146 - Table 'the_vegan_repository.product_shop' doesn't exist
and sometimes:
#2006 - MySQL server has gone away
The product and shop tables do exist with the id field in each. I am doing it in phpmyadmin. What is going on here??
It must have been because my shop table id had unsigned in it. EG
CREATE TABLE `Shop` (
`id` int(6) unsigned NOT NULL,
I removed the unsigned and then it worked.

Error Code: 1215. Cannot add foreign key constraint in MySQL

I have an error code which is Error Code: 1215. Cannot add foreign key constraint in MySQL. My code is
DROP TABLE IF EXISTS Formed;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Band;
DROP TABLE IF EXISTS Customers;
DROP TABLE IF EXISTS Track;
CREATE TABLE Formed(
FormedID int NOT NULL,
YearFormed int,
CountryFormed varchar(50),
CityFormed varchar(50),
BandMembers varchar(400),
PRIMARY KEY(FormedID))
ENGINE=InnoDB;
CREATE TABLE Track (
TrackID int NOT NULL,
AlbumID int NOT NULL,
Songs varchar (100),
TrackNumber varchar (20),
Title varchar (20),
TrackDuration varchar (4),
PRIMARY KEY (TrackID),
FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE)
ENGINE=InnoDB;
CREATE TABLE Album(
AlbumID int NOT NULL,
TrackID int NOT NULL,
BandID int NOT NULL,
Price varchar(5),
PublicationDate varchar(11),
Title varchar(30),
Genre varchar (36),
PRIMARY KEY(AlbumID),
FOREIGN KEY (TrackID) REFERENCES Track(TrackID)ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (BandID) REFERENCES Band(BandID)ON DELETE SET NULL ON UPDATE CASCADE)
ENGINE=InnoDB;
CREATE TABLE Band(
BandID int NOT NULL,
AlbumID int NOT NULL,
RecordLabel varchar(50),
PRIMARY KEY(BandID),
FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE)
ENGINE=InnoDB;
CREATE TABLE Customers (
CustomerID int NOT NULL,
CName varchar (20),
CPhone int (11),
CEmail varchar (50),
CPPaid varchar (50),
CPDate date,
PRIMARY KEY (CustomerID))
ENGINE=InnoDB;
It creates the first table named Formed, but it's giving me the error when it tries and creates the second table and I don't know why. I know a bit about MySQL and I'm teaching myself about Foreign Keys. I have had a look online on why I could be getting this error but couldn't find anything useful.
From the error message, it seems like you are trying to create Track table before Album table and hence, it's failing as it is not able to find parent table (and column) for foreign key constraint.
I would suggest creating the tables with Primary keys only and then, apply foreign key constraints once all 3 tables are created, e.g.:
ALTER TABLE `Track`
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE);
As a rule All reference fields in child tables MUST HAVE index defined on them as like in parent table. They must also follow some other constraints.
As per documentation on foreign key constraints:
REFERENCES parent_tbl_name (index_col_name,...)
Define an INDEX on relevant child columns. And make sure that child column definitions must match with those of their parent column definitions.
Code change suggested:
CREATE TABLE Formed( ... ) -- no change suggested
CREATE TABLE Customers ( ... ) -- no change suggested
CREATE TABLE Band(
...
AlbumID int NOT NULL,
...
KEY (AlbumID), -- <---- add this line
...
);
CREATE TABLE Album(
...
TrackID int NOT NULL,
BandID int NOT NULL,
...
KEY (TrakID), -- <---- add this line
KEY (BandID), -- <---- add this line
...
-- FOREIGN KEY (TrackID) -- <-- add this using ALTER
-- REFERENCES Track(TrackID) -- after creating
-- ON DELETE SET NULL ON UPDATE CASCADE, -- Track table
);
ALTER TABLE Band ADD
FOREIGN KEY ( AlbumID )
REFERENCES Album( AlbumID )
ON DELETE SET NULL ON UPDATE CASCADE;
CREATE TABLE Track ( ... ) -- no changes suggested
ALTER TABLE Album ADD
FOREIGN KEY ( TrackID )
REFERENCES Track( TrackID );
ON DELETE SET NULL ON UPDATE CASCADE;
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

How to add on delete cascade option in mysql?

I created two tables students and orders and I added a foreign key constraint to the order table but I forgot to add on delete cascade option to this table.
table STUDENTS:
CREATE TABLE STUDENTS (
ID varchar(50) NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
)
Table ORDERS
CREATE TABLE Orders
(O_Id int NOT NULL PRIMAY KEY,
Order_No int NOT NULL,ID varchar(50))
Add foreign key to "orders":
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY(ID)
REFERENCES STUDENTS (ID)
I tried this attempt :
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY(ID)
REFERENCES STUDENTS (ID) ON DELETE CASCADE
Thanks.
You have a typo in the Order table. You have PRIMAY where it should be PRIMARY.
After correcting this, I tried creating the tables and all statements worked fine, including the last one.

SQL composite key syntax

I am trying to create a composite key for MYSQL, but i dont know how to, ive tried the following;
CREATE TABLE order_line(
order_id int NOT NULL AUTO_INCREMENT,
car_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (order_id, car_id));
ALTER TABLE order_line ADD CONSTRAINT order_line_FK FOREIGN KEY (order_id) REFERENCES orders (order_id);
ALTER TABLE order_line ADD CONSTRAINT order_line_FK2 FOREIGN KEY (car_id) REFERENCES car (car_id);
you cant have autoincremented key.
See this example of yours makes no sense, on the key you are saying that order_id references orders (order_id), which is fine, but on the table you are saying that this same value is auto-increment, which means that it will be generated by the database.
Remove both AUTO_INCREMENT from your order_line table and you should be fine
if you want you can have a AUTO_INCREMENT order_line_id field on your order_line table as a primary key (which I recommend)
In MySQL you can have only one AUTO_INCREMENT column so you can't define a composite key as AUTO_INCREMENT. Have you tried just
CREATE TABLE order_line(
order_id int NOT NULL,
car_id int NOT NULL,
PRIMARY KEY (order_id, car_id));
Okay, i was able to do it like;
CREATE TABLE order_line (
order_id int NOT NULL,
car_id int NOT NULL);
ALTER TABLE order_line ADD CONSTRAINT order_line_PK PRIMARY KEY (order_id, car_id);
ALTER TABLE order_line ADD CONSTRAINT order_line_FK FOREIGN KEY (order_id) REFERENCES orders (order_id);
ALTER TABLE order_line ADD CONSTRAINT order_line_FK2 FOREIGN KEY (car_id) REFERENCES car (car_id);
CONSTRAINT composite_key_name PRIMARY KEY (col1,col2)