MySQL: How to do foreign keys? - mysql

I wish to have a foreign key in a table but I have no idea how to do it. I wish have a UserID Column in the "wall" table so that I can link back and get the userid's details etc. How would i go about doing this?
Wall Table:
alt text http://img821.imageshack.us/img821/7701/screenshot20100808at010.png
Users Table:
alt text http://img375.imageshack.us/img375/7701/screenshot20100808at010.png

1) In order to have a foreign key column called userid in the WALL table, you need to create the column - skip to #2 if the column already exists:
ALTER TABLE WALL
ADD COLUMN userid INT(25) NOT NULL
If you want to allow WALL records to exist without the userid being specified:
ALTER TABLE WALL
ADD COLUMN userid INT(25) NULL
2) Now you add the foreign key constraint:
ALTER TABLE WALL
ADD FOREIGN KEY (userid) REFERENCES USERS(userid)

Add a UserID column to the Wall table and then create a foreign key on it. In SQL, it'd look like this:
CREATE TABLE Wall (
...
UserID INT,
...
FOREIGN KEY (UserID) REFERENCES User (UserID) ON UPDATE CASCADE ON DELETE RESTRICT,
...
) ENGINE=InnoDB;
Note that you may not want to have ON DELETE RESTRICT. That's the most restrictive option. Read up about it on the MySQL website: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

Related

Can't add foreign key to an existing table

I want to add foreign key to an existing table questions which has 1000 above questions of different categories in it. But when I am trying to add foreign key mysql throws error as below.
#1452 - Cannot add or update a child row: a foreign key constraint fails (question_bank.#sql-af8_1d0, CONSTRAINTcat_idFOREIGN KEY (cat_id) REFERENCESdb_category(cat_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
category table db_category structure.
questions table db_questions structure.
Before adding a foreign key you should ensure it fits with the actual data.
The error is simple, you have some rows on questions table with wrongs value on cat_id
Just delete that rows, or create new categories. You can check the problematic rows with:
SELECT * FROM questions WHERE cat_id NOT IN (SELECT cat_id from category)
You cant add a foreign key to that table because you must check first if the primary key table has a record exists value same with foreign key table.
according to primary column value and foreign key column value.

Alter table to add a foreign key

I am using MySQL.
I have an existing table named school with hundreds of rows data be populated. Now I have another table named student, its primary key is "sid".
I would like to alter my school table to have a foreign key reference to a student.
I tried the following sql statement:
ALTER TABLE school ADD FOREIGN KEY (sid) REFERENCES student(sid);
But I get error:
ERROR 1072 (42000): Key column 'sid' doesn't exist in table
What is the correct way to alter table to add a foreign key to another table?
You have to add the column sid on your table first.
ALTER TABLE school ADD COLUMN sid [INT, VARCHAR2(10];
ALTER TABLE school ADD FOREIGN KEY (sid) REFERENCES student(sid);
PS: I put [INT, VARCHAR2(10] because I don't know what type student(sid) is. Just change to the correct one.
where do you want to link your foreign key?
it seems that you missed the key to link against in the school table:
As far as i can imagine you want to link a student to his school.
So what i'd do is to add a column to the student table:
ALTER TABLE STUDENT
ADD COLUMN SCHOOL_ID INT NOT NULL;
then i'd create the foreign key in STUDENT table to point to SCHOOL
ALTER TABLE STUDENT
ADD FOREIGN KEY (F_SCHOOL_ID) REFERENCES SCHOOL(ID);
This is the best way and not the other way round.

Unable to add foreign key to my table

I'm trying to add a foreign key to my user table.
All of my tables are InnoDB, and are using the same charset. I've got not idea as to why it isn't working :(.
Here is a screenshot of the user table:
As you can see, my userid, is an integer with the max length of 10.
This is the second table (called Content Enabled):
userid, in Content enabler, is identical to the userid in the users table, except it's not a primary index.
When I want to link them via a foreign key, using this query:
ALTER TABLE `contentenabler` ADD FOREIGN KEY ( `userid` ) REFERENCES `tietgen`.`users` (
`userid`
) ON DELETE CASCADE ON UPDATE CASCADE ;
This returns the error Error creating foreign key on userid (check data types)
As far as I can see, the data type are the same, where am I going wrong?
userid is UNSIGNED in your users table, but not your other table.

Multiple foreign keys in one table to one other table in mysql

I got two tables in my database: user and call. User exists of 3 fields: id, name, number and call : id, 'source', 'destination', 'referred', date.
I need to monitor calls in my app. The 3 ' ' fields above are actually userid numbers.
Now I'm wondering, can I make those 3 field foreign key elements of the id-field in table user?
Yes - you can ;-)
Just define all three foreign keys to refer to the id column in User.
Something alike should do the work:
ALTER TABLE call
ADD CONSTRAINT fk_call_source_user FOREIGN KEY (source)
REFERENCES user (id)
ALTER TABLE call
ADD CONSTRAINT fk_call_destination_user FOREIGN KEY (destination)
REFERENCES user (id)
ALTER TABLE call
ADD CONSTRAINT fk_call_referred_user FOREIGN KEY (referred)
REFERENCES user (id)
Alter Table call
ADD FOREIGN KEY (Sourceid) references Source(Id),
FOREIGN KEY (DesId) references Destination(Id)

MySQL Removing Some Foreign keys

I have a table whose primary key is used in several other tables and has several foreign keys to other tables.
CREATE TABLE location (
locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
...
) ENGINE = InnoDB;
CREATE TABLE assignment (
assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
locationID INT NOT NULL,
FOREIGN KEY locationIDX (locationID) REFERENCES location (locationID)
...
) ENGINE = InnoDB;
CREATE TABLE assignmentStuff (
...
assignmentID INT NOT NULL,
FOREIGN KEY assignmentIDX (assignmentID) REFERENCES assignment (assignmentID)
) ENGINE = InnoDB;
The problem is that when I'm trying to drop one of the foreign key columns (ie locationIDX) it gives me an error.
"ERROR 1025 (HY000): Error on rename"
How can I drop the column in the assignment table above without getting this error?
As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.
The syntax is:
ALTER TABLE footable DROP FOREIGN KEY fooconstraint;
The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.
I would think the following query would do it:
ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.
ALTER TABLE your_table_with_fk
drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
drop KEY the_same_name_as_above
Check what's the CONSTRAINT name and the FOREIGN KEY name:
SHOW CREATE TABLE table_name;
Remove both the CONSTRAINT name and the FOREIGN KEY name:
ALTER TABLE table_name
DROP FOREIGN KEY the_name_after_CONSTRAINT,
DROP KEY the_name_after_FOREIGN_KEY;
Hope this helps!
Hey I followed some sequence above,
and found some solution.
SHOW CREATE TABLE footable;
You will get FK Constrain Name like
ProjectsInfo_ibfk_1
Now you need to remove this constraints. by alter table commantd
alter table ProjectsInfo drop foreign key ProjectsInfo_ibfk_1;
Then drop the table column,
alter table ProjectsInfo drop column clientId;
Here's a way to drop foreign key constraint, it will work.
ALTER TABLE location.location_id
DROP FOREIGN KEY location_ibfk_1;
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key region_ibfk_1;
or
more simply just type:-
alter table TableName drop foreign key TableName_ibfk_1;
remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1
first need to get actual constrain name by this query
SHOW CREATE TABLE TABLE_NAME
This query will result constrain name of the foreign key, now below query will drop it.
ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1
last number in above constrain name depends how many foreign keys you have in table
You can not drop the foreign key column because it is being referenced from the table assignmentStuff. So you should first drop the foreign key constraint assignmentStuff.assignmentIDX.
A similar question has already been asked here. Check also here for more info.
Try this:
alter table Documents drop
FK__Documents__Custo__2A4B4B5E
step1: show create table vendor_locations;
step2: ALTER TABLE vendor_locations drop foreign key vendor_locations_ibfk_1;
it worked for me.