InnoDb how to create a foreign key - mysql

I have a table articles and I want to create another table summaries that is a child of articles table.
I've used the following sql to create summaries table but however mysql keeps throwing an error #1072 - Key column 'article_id' doesn't exist in table
CREATE TABLE summaries(
summary_id INT NOT NULL AUTO_INCREMENT,
summary TEXT,
PRIMARY KEY ( summary_id),
FOREIGN KEY (article_id) REFERENCES articles(article_id)
)ENGINE=INNODB;

you dont have article_id in your table summaries, you may mean this:
FOREIGN KEY (summary_id) REFERENCES articles(article_id)
if you want make summary_id as foreign key to article_id in articles table.
But make sure they have same structure properties.
EDIT:
or create a column article_id in summaries table and make it foreign key
CREATE TABLE summaries(
summary_id INT NOT NULL AUTO_INCREMENT,
summary TEXT,
article_id INT,
PRIMARY KEY ( summary_id),
FOREIGN KEY (article_id) REFERENCES articles(article_id)
)ENGINE=INNODB;
EDIt:
INSERT INTO `summaries` (summary,article_id)
VALUES ($yoursummryVar , (SELECT article_id
FROM articles
WHERE ........)
)
i didnt test it.

Related

Changing the Reference value of a Foreign Key

I have created a table 'company' having the column actor_id referencing the primary key (id) of the table 'actor'. Now I want to change the column actor_id to reference the primary key (id) of the table director. After trying to drop the foreign key, and creating a new one referencing the new table, it did not work as desired, it stayed the same - referencing the previous (actor) table. What changes should I make?
CREATE TABLE company(
id INT NOT NULL AUTO_INCREMENT,
actor_id INT NOT NULL,
CONSTRAINT aID FOREIGN KEY (actor_id) REFERENCES actor(id),
PRIMARY KEY(id)
);
ALTER TABLE company
DROP FOREIGN KEY aID,
ADD CONSTRAINT actID FOREIGN KEY (actor_id) REFERENCES director(id);
Don't see any apparent issues in the code above. I tried same in SQL Fiddle which works. You can check the link.
http://www.sqlfiddle.com/#!9/82e334c/2/0

How to fix foreign key constraint when trying to references two primary keys from the same table?

Misson:
I'm trying to create two tables in MySQL, the first table has two primary keys (composite). The second table has three, two of which are foreign keys that reference the first tables two primary keys. So now I'm trying to bridge them, which isolates the problem code and can be seen below.
Issue:
MySQL workbench refuses allow me to create a table that references another table's two primary keys. It just gives me the error code: 1215. Cannot add foreign key constraint.
I tried:
Changing the attribute types from datetime to varchar(). Changing the attribute names. Checked spelling 5 times. Referencing only one key works fine, but I need both.
Problem Code (SQL Table):
CREATE TABLE IF NOT EXISTS TestInformation2
(
WorkOrder varchar(15),
Date datetime,
TechnicianID smallint,
Primary key (WorkOrder, Date)
) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS TestBridge2
(
TestBridgeID integer Primary key,
WorkOrder varchar(15),
Date datetime,
Foreign key (WorkOrder) references TestInformation (WorkOrder),
Foreign key (Date) references TestInformation (Date)
) ENGINE = InnoDB;
Result I want:
Create the table 'TestBridge' which has the two foreign key attributes: WorkOrder and Date
It should be one composite foreign key, not two:
CREATE TABLE `TestBridge2` (
`TestBridgeID` INTEGER NOT NULL,
`WorkOrder` VARCHAR(15),
`Date` DATETIME,
PRIMARY KEY (`TestBridgeID`),
CONSTRAINT FOREIGN KEY (`WorkOrder`, `Date`) REFERENCES `TestInformation2` (`WorkOrder`, `Date`)
)
ENGINE=InnoDB;
One single foreign key has to be created for this like:
CREATE TABLE IF NOT EXISTS TestBridge2
(
TestBridgeID integer Primary key,
WorkOrder varchar(15),
Date datetime,
Foreign key (WorkOrder, Date) references TestInformation2 (WorkOrder, Date)
) ENGINE = InnoDB;

How to add foreign key to table in mysql

What I am doing incorrect? Trying to create these tables in sqlfiddle
does not work gives
Cannot add foreign key constraint
create table product (
pid int NOT NULL,
name varchar(10),
PRIMARY KEY (pid)
);
create table trans (
tid int NOT NULL ,
productId int NOT NULL,
userId int NOT NULL,
PRIMARY KEY (tid),
FOREIGN KEY (productId) REFERENCES product(pid),
FOREIGN KEY (userId) REFERENCES user1(uid)
);
create table user1 (
uid int NOT NULL ,
location varchar(22),
PRIMARY KEY (uid)
);
As #BillKarwin mentioned, the definitions for tables containing primary keys referenced by the trans table should appear before the definition for the trans table. So you should move the definition for the trans table to last.
However, even doing this still results in an error in SQLFiddle:
SQLFiddle (uncomment the foreign key reference in trans)
SQLFiddle seems to have some sort of problem with accepting this table schema. This is not surprising, as the site seems to have such problems frequently.
What is order you create tables. You need first to create product and user1 and at the end - trans.

Altering MySQL table to add foreign key constraint leads to errors

Question:
Why am I getting errors when trying to alter a table with a foreign key constraint?
Details:
I have 1 table, HSTORY which I use as a base table for all other specific history tables (ie. USER_HISTORY, BROWSER_HISTORY, PICTURE_HISTORY...). I have also included the PICTURE and USER tables as they get called as well.
HISTORY table:
CREATE TABLE IF NOT EXISTS HISTORY
(
ID INT NOT NULL AUTO_INCREMENT,
VIEWERID INT NOT NULL ,
VIEWDATE TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (ID),
FOREIGN KEY (VIEWERID) REFERENCES USER(ID)
)
engine=innodb;
USER table: (in case anyone is curious)
CREATE TABLE IF NOT EXISTS USER
(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
engine=innodb;
PICTURE table: (in case anyone is curious)
CREATE TABLE IF NOT EXISTS PICTURE
(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
engine=innodb;
PICTURE_HISTORY table:
CREATE TABLE IF NOT EXISTS PICTURE_HISTORY LIKE HISTORY;
ALTER TABLE PICTURE_HISTORY
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
However, when I do this, I get:
Key column 'FOREIGNID' doesn't exist in table
I take this to mean that I have to first create FOREIGNID, but in many of the examples on SO, the above should work. Anyone know why this is occurring?
Thanks to Michael for pointing out my mistake. I can't actually make a foreign key unless the column already exists. If instead I issue these two commands, the foreign key constraint is created:
ALTER TABLE PICTURE_HISTORY
ADD COLUMN FOREIGNID INT NOT NULL;
ALTER TABLE PICTURE_HISTORY
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
You can combine commands for mysql using a comma, like so:
ALTER TABLE PICTURE_HISTORY
ADD COLUMN FOREIGNID INT NOT NULL,
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);

How do I create a MySQL table when it has two foreign keys?

What would be the code for creating a table with two foreign keys?
I have a USER table and a PICTURE table. Since a USER can be in many PICTURE and many PICTURE can be from a USER, I need a third table with both primary keys.
Thank you SO, as usual you are invaluable for a learning novice. :)
I can't speak specifically for mySQL but in most databases I have worked with you can put as many foreign keys as you need on a table. But you can only have one primary key. A third table with both keys is the right choice. Make a foreign key to each of the other two tables and a primary key consisting of both ids in the table.
If I understood correctly, you may need to do something like the following:
CREATE TABLE users (
user_id INT NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL
) ENGINE=INNODB;
CREATE TABLE pictures (
picture_id INT NOT NULL PRIMARY KEY,
filename VARCHAR(255) NOT NULL,
posted_by INT NOT NULL,
FOREIGN KEY (posted_by) REFERENCES users(user_id)
) ENGINE=INNODB;
CREATE TABLE users_in_pictures (
user_id INT NOT NULL,
picture_id INT NOT NULL,
PRIMARY KEY (user_id, picture_id),
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (picture_id) REFERENCES pictures(picture_id)
) ENGINE=INNODB;
Note that each picture can be posted by a user. In fact the posted_by field is constrained by a foreign key that references the users table.
In addition, I assume that you want to tag pictures ala-facebook. In this case, you can use the third table, which is using a composite primary key on (user_id, picture_id) and both fields are also constrained to the appropriate table.