I am trying to add Category_Name as a foreign key to the ITEM table. Category_Name exists in CATEGORY table and this is what i get:
mysql> use acmeonline;
Database changed
mysql> show tables;
+----------------------+
| Tables_in_acmeonline |
+----------------------+
| category |
| item |
+----------------------+
2 rows in set (0.00 sec)
mysql> describe item;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Item_Number | int(11) | NO | PRI | 0 | |
| Item_Name | varchar(35) | YES | | NULL | |
| Model_Num | varchar(15) | YES | | NULL | |
| Description | varchar(255) | YES | | NULL | |
| Price | double(8,2) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
5 rows in set (0.07 sec)
mysql> describe category;
+------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+-------------+------+-----+---------+-------+
| Category_Name | varchar(35) | NO | PRI | | |
| ShippingPerPound | double(4,2) | YES | | NULL | |
| DiscountAllowed | char(1) | YES | | NULL | |
+------------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> ALTER TABLE item
-> ADD CONSTRAINT fk_category_name
-> FOREIGN KEY(Category_Name)
-> REFERENCES Category(Category_Name);
ERROR 1072 (42000): Key column 'Category_Name' doesn't exist in table
How do I fix this? Please bear with me because I did look at some sites on how to do it, but I get the same results.
You need to add the CATEGORY_NAME column on ITEM TABLE, or map the foreign key to another existing column in ITEM.
Either:
ALTER TABLE ITEM
ADD CATEGORY_NAME VARCHAR(35) NOT NULL;
ALTER TABLE ITEM
ADD CONSTRAINT FK_CATEGORY_NAME
FOREIGN KEY (CATEGORY_NAME)
REFERENCES CATEGORY (CATEGORY_NAME);
OR
ALTER TABLE ITEM
ADD CONSTRAINT FK_CATEGORY_NAME
FOREIGN KEY (SOME_OTHER_EXISTING_COLUMN)
REFERENCES CATEGORY (CATEGORY_NAME);
You must first add the column in a separate alter statement:
alter table item add column category_name varchar(35);
Foreign key constraints only create a relationship between tables - they don't also create the column(s) involved.
Related
I use this query:
ALTER TABLE recent_article_entry ADD FOREIGN KEY (`article`) REFERENCES article(`id`);
Or this:
ALTER TABLE recent_article_entry ADD CONSTRAINT fk_rae_article FOREIGN KEY (article) REFERENCES article(id);
And it says No errors; 1 row affected, taking 127 ms.
Which row was affected?
If I go to information_schema.KEY_COLUMN_USAGE, I don't see my newly generated foreign key there. And if I try to add to recent_article_entry, constraints are not enforced.
I'm very confused. I tried to debug the query by changing some of the values to jibberish.
So:
ALTER TABLE sldakjfalksdjf ADD FOREIGN KEY (`article`) REFERENCES article(`id`);
fails as expected, and
ALTER TABLE recent_article_entry ADD FOREIGN KEY (`aslkdjfalksjdf`) REFERENCES article(`id`);
fails as expected.
But for whatever reason,
ALTER TABLE recent_article_entry ADD FOREIGN KEY (`article`) REFERENCES aslkdjfdkf(`id`);
succeeds fine (as well as changing the referenced column to jibberish). I've made plenty of foreign keys before. Why is MySQL suddenly ignoring my queries and not creating the foreign key?
Edit At the request of ray, here is the output of the describe statements:
describe recent_article_entry:
Field |Type |Null|Key|Default|Extra
-------------|-----------|----|---|-------|-----
article |varchar(55)|NO |PRI| |
file_location|varchar(55)|NO |PRI| |
describe article
Field |Type |Null |Key|Default |Extra
--------------|--------------|-----|---|-----------------|-----
id |varchar(55) |NO |PRI| |
title |varchar(255) |YES | |NULL |
author |varchar(55) |NO |MUL| |
translator |varchar(55) |NO |MUL| |
source |varchar(1000) |YES |MUL|0 |
published_flag|tinyint(1) |NO | | |
published |timestamp |YES | |CURRENT_TIMESTAMP|
short_title |varchar(55) |YES | |NULL |
describe file_location
Field |Type |Null |Key|Default |Extra
------|-----------|-----|---|-----------------|-----
id |varchar(55)|NO |PRI| |
views |int(11) |YES | |NULL |
And the version is 5.1.56-log
Possible Cause - Collations and Encodings
I've often seen MySQL not be informative enough when trying to create FK constraints between tables. One particular instance where I got burned years ago was the table collation and/or string encodings for the column in question. They have to match in both tables. In other words, you should verify that if your VARCHAR PK column in some table A is using latin1 encoding, then the VARCHAR FK column in some table B must also be using latin1 enconding and not something else, like utf8.
In this next section, I reproduce your basic setup, but I made sure that the table collation and column encodings were the same. In my case, they're default, but you should check your own database tables to be sure.
Possible Cause - Storage Engine
In older version of MySQL (you're using 5.1, I'm using 5.7) the default storage engine is MyISAM. This storage engine is not ACID-compliant. Therefore, it does not support foreign key constraints. You must make sure your storage engine is set to InnoDB for each table.
You can specify this as the default in your MySQL config file or as part of the create table SQL statement. Currently, this one seems a bit more likely because you say your query is not producing error messages. That being said, I don't immediately recall if the previous possibility produces messages or remains silent.
In the next section I show that this is working normally, at least for me, including the query you've provided.
Creating Tables
I've tried to reproduce some of the basics for your tables, enough to get PKs and FKs setup between them. They're reproduced below, including the create statements:
mysql> create table `test`.`article` (
`id` varchar(55) not null,
`title` varchar(255) null default null,
primary key (`id`)
);
Query OK, 0 rows affected (0.42 sec)
mysql> create table `test`.`file_location` (
`id` varchar(55) not null,
`views` int(11) null default null,
primary key (`id`)
);
Query OK, 0 rows affected (0.35 sec)
mysql> create table `test`.`recent_article_entry` (
`article` varchar(55) not null,
`file_location` varchar(55) not null,
primary key (`article`, `file_location`)
);
Query OK, 0 rows affected (0.32 sec)
The tables are described below:
mysql> show tables;
+----------------------+
| Tables_in_test |
+----------------------+
| article |
| file_location |
| recent_article_entry |
+----------------------+
3 rows in set (0.00 sec)
mysql> describe article;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | varchar(55) | NO | PRI | NULL | |
| title | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> describe file_location;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | varchar(55) | NO | PRI | NULL | |
| views | int(11) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> describe recent_article_entry;
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| article | varchar(55) | NO | PRI | NULL | |
| file_location | varchar(55) | NO | PRI | NULL | |
+---------------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Creating Constraints
Here we check the column usage prior to the foreign keys being added and note that they don't show up because they don't yet exist:
mysql> select TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME from information_schema.KEY_COLUMN_USAGE;
+----------------------+---------------+-------------------------+-----------------------+------------------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_SCHEMA | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+----------------------+---------------+-------------------------+-----------------------+------------------------+
| article | id | NULL | NULL | NULL |
| file_location | id | NULL | NULL | NULL |
| recent_article_entry | article | NULL | NULL | NULL |
| recent_article_entry | file_location | NULL | NULL | NULL |
+----------------------+---------------+-------------------------+-----------------------+------------------------+
4 rows in set (0.00 sec)
I went ahead and created the FKs with the following query in my test database:
alter table `test`.`recent_article_entry`
add constraint `fk_recent_article_entry_article_id`
foreign key (`article`)
references `test`.`article` (`id`)
on delete restrict
on update cascade,
add constraint `fk_recent_article_entry_file_location`
foreign key (`file_location`)
references `test`.`file_location` (`id`)
on delete restrict
on update cascade;
I then checked the information_schema as I had done before. You can now see the constraints listed:
mysql> select TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME from information_schema.KEY_COLUMN_USAGE;
+----------------------+---------------+-------------------------+-----------------------+------------------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_SCHEMA | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+----------------------+---------------+-------------------------+-----------------------+------------------------+
| article | id | NULL | NULL | NULL |
| file_location | id | NULL | NULL | NULL |
| recent_article_entry | article | NULL | NULL | NULL |
| recent_article_entry | file_location | NULL | NULL | NULL |
| recent_article_entry | article | test | article | id |
| recent_article_entry | file_location | test | file_location | id |
+----------------------+---------------+-------------------------+-----------------------+------------------------+
6 rows in set (0.00 sec)
I know my query looks different compared to yours, but yours works fine for me too, as I'll show next. I dropped the FKs shown above and then gave your own query a try:
mysql> alter table recent_article_entry add foreign key (`article`) references article(`id`);
Query OK, 0 rows affected (0.56 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME from information_schema.KEY_COLUMN_USAGE;
+----------------------+---------------+-------------------------+-----------------------+------------------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_SCHEMA | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+----------------------+---------------+-------------------------+-----------------------+------------------------+
| article | id | NULL | NULL | NULL |
| file_location | id | NULL | NULL | NULL |
| recent_article_entry | article | NULL | NULL | NULL |
| recent_article_entry | file_location | NULL | NULL | NULL |
| recent_article_entry | article | test | article | id |
+----------------------+---------------+-------------------------+-----------------------+------------------------+
As you can see, your own query worked fine for me. Let me know in the comments if you have additional questions or spot something you think I might've missed.
I'm making a database in MySQL in class and I'm having trouble adding foreign keys to my tables. I already added most of the foreign keys to my tables when I created the tables but obviously I couldn't add all of them in the creation process. I'm trying to add the remaining foreign keys with the below method.
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
For some reason the error message listed in the title keeps popping up. The code is below. I can see the tables are coming out a bit funny but if you read them from left to right you can see what it says. What do you think?
mysql> show columns from games;
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| gameID | int(11) | NO | PRI | NULL | auto_increment |
| videoGames | varchar(30) | NO | | NULL | |
| year | int(11) | NO | | NULL | |
| genreID | int(11) | NO | MUL | NULL | |
| companyID | int(11) | NO | MUL | NULL | |
| directorID | int(11) | NO | MUL | NULL | |
+------------+-------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)
mysql> show columns from consoles;
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| consoleID | int(11) | NO | PRI | NULL | auto_increment |
| console | varchar(20) | NO | | NULL | |
| yearReleased | int(11) | NO | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
mysql> alter table games
-> add foreign key(consoleID) references consoles(consoleID);
ERROR 1072 (42000): Key column 'consoleID' doesn't exist in table
There is no field consoleID in your table games. You need to create it before trying to add a constraint on it. This will add consoleID and create the constraint:
ALTER TABLE games ADD COLUMN consoleID INTEGER NOT NULL;
ALTER TABLE games ADD FOREIGN KEY (consoleID) REFERENCES consoles(consoleID);
You should think about adding a third table where you associate consoles with games because some games are multiplateform. :)
I am preparing for an exam and I decided to do some example tasks I made up but I am stuck on one particular. Relationships. I have been hitting my head against the wall of SQL for 3-4 hours with little progress. I have 2 tables in which I want to create a one to one and a one to many relationships.
CREATE TABLE article (
price INT(30) NOT NULL,
published_on DATE NOT NULL
);
CREATE TABLE tag(
descption VARCHAR(30) NOT NULL,
priority INT(30) NOT NULL
);
CREATE TABLE category(
date_created_on DATE NOT NULL,
name VARCHAR(30) NOT NULL
);
INSERT INTO article VALUES (10.0, "2001-01-01", 0);
INSERT INTO article VALUES (20.0, "1992-05-08", 0);
INSERT INTO tag VALUES ("wtf", 1, 1);
INSERT INTO tag VALUES ("is this", 2, 2);
ALTER TABLE article ADD article_id INT(30) NOT NULL;
ALTER TABLE article ADD PRIMARY KEY(article_id);
ALTER TABLE article MODIFY article_id AUTO_INCREMENT;
ALTER TABLE tag ADD tag_id INT(30) NOT NULL;
ALTER TABLE tag ADD PRIMARY KEY(tag_id);
ALTER TABLE tag MODIFY tag_id AUTO_INCREMENT;
ALTER TABLE tag ADD FOREIGN KEY (tag_id) REFERENCES (article_id);
I want to make it so that one article has a one to one with article, then to make it so article has a one to many with category. I can't do the one to one to even try the one to many. Can you please give me some insight as to how to make it happen and how the relationships will work?
Here is the information from inside the database -
mysql> select * from Tag;
+-------------+----------+--------+
| description | priority | tag_id |
+-------------+----------+--------+
| wtf | 1 | 1 |
| is this | 2 | 2 |
+-------------+----------+--------+
mysql> select * from Article;
+-------+--------------+------------+
| price | published_on | article_id |
+-------+--------------+------------+
| 10 | 2001-01-01 | 7 |
| 20 | 1992-05-08 | 8 |
+-------+--------------+------------+
mysql> describe Article;
+--------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+----------------+
| price | decimal(30,0) | YES | | NULL | |
| published_on | date | YES | | NULL | |
| article_id | int(30) | NO | PRI | NULL | auto_increment |
+--------------+---------------+------+-----+---------+----------------+
mysql> describe Tag;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| description | varchar(30) | NO | | NULL | |
| priority | int(30) | NO | | NULL | |
| tag_id | int(30) | NO | PRI | NULL | |
+-------------+-------------+------+-----+---------+-------+ mysql> select * from Tag;
+-------------+----------+--------+
| description | priority | tag_id |
+-------------+----------+--------+
| wtf | 1 | 1 |
| is this | 2 | 2 |
+-------------+----------+--------+
mysql> select * from Article;
+-------+--------------+------------+
| price | published_on | article_id |
+-------+--------------+------------+
| 10 | 2001-01-01 | 7 |
| 20 | 1992-05-08 | 8 |
+-------+--------------+------------+
mysql> describe Article;
+--------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+----------------+
| price | decimal(30,0) | YES | | NULL | |
| published_on | date | YES | | NULL | |
| article_id | int(30) | NO | PRI | NULL | auto_increment |
+--------------+---------------+------+-----+---------+----------------+
mysql> describe Tag;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| description | varchar(30) | NO | | NULL | |
| priority | int(30) | NO | | NULL | |
| tag_id | int(30) | NO | PRI | NULL | |
+-------------+-------------+------+-----+---------+-------+
And this is the error I get for creating the foreign key:
mysql> ALTER TABLE Tag ADD FOREIGN KEY(tag_id) REFERENCES Article(article_id);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`exam_example`.`#sql-2836_1`,
CONSTRAINT `#sql-2836_1_ibfk_1` FOREIGN KEY (`tag_id`) REFERENCES `Article` (`article_id`))
CREATE TABLE article (
price INT(30) NOT NULL,
published_on DATE NOT NULL,
article_id INT(30) NOT NULL,
CONSTRAINT pk_article_id PRIMARY KEY(article_id)
);
CREATE TABLE tag(
descption VARCHAR(30) NOT NULL,
priority INT(30) NOT NULL,
tag_id INT(30) NOT NULL,
CONSTRAINT pk_tag_article PRIMARY KEY(tag_id),
CONSTRAINT fk_tag_article FOREIGN KEY(tag_id) REFERENCES article(article_id)
);
INSERT INTO article VALUES (10.0, "2001-01-01", 0);
INSERT INTO article VALUES (20.0, "1992-05-08", 1);
INSERT INTO tag VALUES ("wtf", 1, 1);
INSERT INTO tag VALUES ("is this", 2, 2);
This is a relationship one to one.
I'm saying here that the primary key of the tag is the same from article.
What I try to accomplish is that I want to update rows in tableA when one row from tableB gets deleted.
The layout of tableA is this:
+----------------------------+--------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------------+--------------+------+-----+---------------------+----------------+
| user_id | int(11) | NO | PRI | NULL | auto_increment |
| nickname | varchar(32) | NO | | NULL | |
| password | varchar(129) | NO | | NULL | |
| mafia_id | int(11) | NO | | 0 | |
+----------------------------+--------------+------+-----+---------------------+----------------+
and of tableB this:
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| mafia_id | int(11) | NO | PRI | NULL | auto_increment |
| mafia_name | varchar(32) | NO | | | |
| mafia_tag | varchar(5) | NO | | | |
| mafia_color | int(11) | NO | | 0 | |
| mafia_car | int(11) | NO | | 0 | |
| mafia_base | int(11) | NO | | 0 | |
+-------------+-------------+------+-----+---------+----------------+
I want to set all tableA.mafia_id to 0 when the corresponding mafia_id in tableB is deleted.
I read in the documentation that the database will automaticly do it for you, but you have to specify some stuff at table creation (in CREATE TABLE, create_definition: | CHECK (expr)?). The documentation is a bit unclear to me.
I also read this topic:
Create a trigger that updates a column on one table when a column in another table is updated
but this doesn't apply to me, i think?
So how would I create such a table (create table ...) or delete row statement?
Thanks in advance!
Since you are using InnoDB, you can achieve this with a foreign key constraint:
ALTER TABLE tableA
MODIFY mafia_id INT(11) NULL,
ADD FOREIGN KEY (mafia_id) REFERENCES tableB (mafia_id) ON DELETE SET NULL
As explained in the manual:
SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child table to NULL. This is valid only if the foreign key columns do not have the NOT NULL qualifier specified. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.
If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.
Note that the constraint has the additional advantage of ensuring that mafia_id values in tableA must always reference an existing record in tableB.
alter table if field is not already exist
ALTER TABLE `table`
ADD( `abc` text NOT NULL,
`xyz` tinyint(1) NOT NULL,
);
if abc or xyz fields are already exist the can not be alter table
if it is possible ?
You can use a SHOW COLUMNS beforehand and construct your query accordingly, adding only fields that are missing.
Example output of SHOW COLUMNS:
mysql> SHOW COLUMNS FROM City;
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| Country | char(3) | NO | UNI | | |
| District | char(20) | YES | MUL | | |
| Population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
I can't comment yet, so I post answer: try this link for detailed example. It queries information_schema.COLUMNS table for column information about database tables.