Error While make a relationship in mysql with 2 (varchar columns) - php

First table users
id name
---------------------
1 John
Second table orders
id order name
----------------------------------
1 pencil John
The sql code to make a relationship with first column name in table users
And second column name in table orders
ALTER TABLE orders
ADD CONSTRAINT user_name
FOREIGN KEY(name) REFERENCES users(name)
ON UPDATE CASCADE
ON DELETE CASCADE;
it give me error
errno: 150 "Foreign key constraint is incorrectly formed"
How to Fix this proplem ??

So after searching I found that the solution is very simple :D
use the same sql code
ALTER TABLE orders
ADD CONSTRAINT user_name
FOREIGN KEY(name) REFERENCES users(name)
ON UPDATE CASCADE
ON DELETE CASCADE;
and make name unique in the parent column .

Related

How to create a foreign key in phpmyadmin

I want to make doctorid a foreign key in my patient table.
So I have all of my tables created - the main problem is that when I go to the table > structure > relation view only the primary key comes up that I can create a foreign key (and it is already the primary key of the certain table that I want to keep - i.e Patient table patient is enabled to be changed but the doctor Id -I have a doctor table also- is not enabled).
I have another table with two composite keys (medicineid and patientid) in relation view it enables me to change both
Do I have to chance the index of doctor ID in patient table to something else? both cannot be primary keys as patient ID is the primary for the patient table - doctor is the foreign.
I hope anyone can help
Kind regards
You can do it the old fashioned way... with an SQL statement that looks something like this
ALTER TABLE table_1_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (table_1_column_name)
REFERENCES target_table(target_table_column_name);
For example:
If you have books table with column created_by which refers to column id in users table:
ALTER TABLE books
ADD CONSTRAINT books_FK_1
FOREIGN KEY (created_by)
REFERENCES users(id);
This assumes the keys already exist in the relevant table
The key must be indexed to apply foreign key constraint. To do that follow the steps.
Open table structure. (2nd tab)
See the last column action where multiples action options are there. Click on Index, this will make the column indexed.
Open relation view and add foreign key constraint.
You will be able to assign DOCTOR_ID as foreign now.
To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab.
Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.
Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.
See attachments. I hope this could be useful for anyone.
Create a categories table:
CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
Create a products table and reference categories table:
CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;
Create a vendors table and modify products table:
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key (referencing vendors table) to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
If you wish to drop that key then:
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
In phpmyadmin, Go to Structure tab, select Relation view as shown in image below.
Here you will find the tabular form to add foreign key constrain name, current table column, foreign key database, table and column

foreign key prevents deletion of data in mysql

I'm designing a website of book library for my project in php.
Anyways I have three tables named books,users and savebook.
Table book has following columns: "bookid", "title","author" "genre" and "summary".
And table users has following columns userid, username, password, and name.
Users can save books as favorites and those saved books are saved in the table named savebook with columns bookid and userid which are foreign key to table book and users
I used following query for that:
ALTER TABLE savebook
ADD CONSTRAINT bkid_usid
FOREIGN KEY (bookid)
REFERENCES books (bookid);
and
ALTER TABLE savebook
ADD CONSTRAINT usid_bkid
FOREIGN KEY (userid)
REFERENCES users(userid);
Now the problem is whenever i try to delete a book from table book using query
DELETE FROM books
WHERE bookid=1;
I get this message:
1451 - Cannot delete or update a parent row: a foreign key constraint fails (booklibrary.savebook, CONSTRAINT bkid_usid FOREIGN KEY (bookid) REFERENCES books (bookid))
How do i delete a book from table book which also deletes the related row in table savebook?
To get the behavior you describe, you can specify
ON DELETE CASCADE
as part of the foreign key definition.
Reference: http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html
If you were to modify your foreign key constraint bkid_usid (on the booksave table), then the delete statement that you show
DELETE FROM books WHERE ...
Would cause MySQL to delete the rows in booksave that have a foreign key values that reference rows being removed from books.
ALTER TABLE savebook
ADD CONSTRAINT bkid_usid
FOREIGN KEY (bookid)
REFERENCES books (bookid)
ON DELETE CASCADE
;
Make note of that last line I added to the ALTER from the original question, it is an optional part of the foreign key definition (there is also ON UPDATE ...). By default, when not specified, I believe MySQL treats it as NO ACTION or RESTRICT (those two are effectively the same as far as I know) instead of CASCADE. Full documentation found at http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
An interesting question :)
I think the problem is caused by the so called "referential integrity".
That means, that you are not able to delete a dataset, which primary key is used in another tables dataset as foreign key. If you could do this, some foreign keys of the table savebook would refer to a dataset in table books, that doesn't exist anymore.
So first you have to delete all datasets in savebook, where the bookid is the same one as of the book you want to delete and after that, you can delete this dataset from books. ;)
You have applied constraints to the tables. You need to tell MySQL to delete referenced entries from "savebook" table if any entry is deleted from "book" table.
ALTER TABLE savebook ADD CONSTRAINT bkid_usid FOREIGN KEY (bookid) REFERENCES books (bookid) ON DELETE CASCADE

Relate DB id's Mysql

I would like to know how can I relate 2 id's. One frome users table and another from stats table. The id from users is AI , Primary and I want to relate the other id to this one.
I tried Foreign key constraint (INNODB) and it gave me this error #1452 - Cannot add or update a child row: a foreign key constraint fails (game.#sql-3de_34f, CONSTRAINT ?sql?3de_34f_ibfk_1 FOREIGN KEY (id) REFERENCES user (id)) .
Thanks
Try this!
SET foreign_key_checks = 0;
Then run query to add your key, and after that...
SET foreign_key_checks = 1;
You have USER_IDs in your "stats" table that are not in your "users" table.
Delete them if you think they are not useful anymore.
DELETE FROM stats where user_id NOT IN (SELECT user_id from users);
Then, you can create your reference keys.

unable to create a foreign key constraint

I have a clients, feedback and a repairs tables. A client can give many feedbacks and have many repairs. In the feedback table I have created a clientid column (added also index) and I am able to create a foreign key to the clientid column (primary key) of the clients table.
The problem is that I am unable to do the same with the repairs table. Even though I have created a clientid column (indexed) within the repairs table and it has the same properties as the clientid within the clients table I get the following:
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint
fails (ccsdb.,
CONSTRAINT #sql-3f0_8e5_ibfk_1 FOREIGN KEY (client_id) REFERENCES
clients (client_id) ON DELETE CASCADE ON UPDATE CASCADE)
That error (Cannot add or update a child row: a foreign key constraint fails) is referenced in the MySQL FK Doc
To add a reference between 2 tables the condition must fit for existing data.
That means if you say table1.id = table2.id then all ids of table1 and table2 must match together.
To solve that you have to eliminate or fix those rows that don't match.
Example:
table1.id | table2.fk
1 | 1 ok
2 | null error
3 | 4 error if id 4 is not in table1

phpmyadmin doesnt allow me to add primary/foreign key relationship

That is the primary table field (tasks table):
task_id int(10) UNSIGNED No None AUTO_INCREMENT
This is my foreign table field (url_error_stats table):
task_id int(10) UNSIGNED No None
url_error_stats doesnt present the "relation view" option to connect between the keys..why?
SQL query:
ALTER TABLE url_error_stats ADD FOREIGN KEY ( task_id )
REFERENCES aws_backlinks.tasks (
task_id ) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL said:
1452 - Cannot add or update a child row: a foreign key constraint
fails (aws_backlinks., CONSTRAINT #sql-6f0_3bd_ibfk_1 FOREIGN KEY
(task_id) REFERENCES tasks (task_id) ON DELETE CASCADE ON UPDATE
CASCADE)
you have to use innodb and index the primary key if you want to create the foreign keys. and I will recommend you to use NAVICAT . its much easier to create foreign keys and quick too. but for a quick phpmyadmin guide see
Setting up foreign keys in phpMyAdmin?
Another reason can be the unrelated data in your tables. I mean you may have a foreign key that doesn't exist in parent table.
in this , click on url_error_stats table, then on right hand side it will show all the fields list, so now check on checkbox of that particular field which u wanted to be foreign and click on the link relation view (which is provided by phpmyadmin below to the table fields with blue color hyperlink).
it will open relationship screen , there You can select the field of the primary table.
Thanks

Categories