phpmyadmin doesnt allow me to add primary/foreign key relationship - php

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

Related

SQL::PDO remove path to image from db if recipe is removed [duplicate]

I am trying to figure out relationships and deletion options.
I have two tables, User and UserStaff, with a 1:n relationship from User to UserStaff (a user can have multiple staff members).
When my User is deleted, I want to delete all of the UserStaff tables associated with that User. When my UserStaff is deleted, I don't want anything to happen to User. I understand that this is a cascading relationship, but I'm not sure which way.
i.e. Do I select the existing foreign key in my UserStaff table and make it cascading, or do I create a new foreign key in User and set that to cascading?
Yes, it's possible. You should make the FK in UserStaff table. In this way:
User Table
CREATE TABLE `User` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
UserStaff Table
CREATE TABLE `UserStaff` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`UserId` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`),
KEY `UserId` (`UserId`),
CONSTRAINT `UserStaff_ibfk_1`
FOREIGN KEY (`UserId`)
REFERENCES `User` (`Id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
From Wikipedia:
CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).
Here, User is the master table, and UserStaff is the child table. So, yes, you'll want to create the foreign key in UserStaff, with ON DELETE CASCADE
It's been a while since I've used this, but here goes (btw, I use Toad for MySql - a great IDE, and it's free too - http://www.toadworld.com/Freeware/ToadforMySQLFreeware/tabid/561/Default.aspx!)
You need to add a Constraint to the User table. If you have an id column (and the corresponding foreign userid key in UserStaff) then the SouceColumn should be id, the destination table UserStaff and the destination column userid. You can then set the OnDelete action to be 'Cascade'
The other options are pretty self-explanatory - Restrict limits values to the values in the source column, Set Null sets the foreign key matches to Null and No Action does, er, nothing.
This stuff is very easy to do via the Toad IDE. I used MySqlAdmin tools for ages but recently discovered Toad (and it has diff and compare tools too!).
The ON DELETE CASCADE is specified on the foreign key in the UserStaff table. For additional info on foreign keys the MySQL documentation has a number of examples. The User table does not have a foreign key pointing to UserStaff, so it will not be affected by changes to the UserStaff table.
The easiest way might be to make two quick tables and try it out. But since you didn't I can tell you that the outcome will be that it work the way that you want to.
When you have a table User and a table UserStaff were a field in UserStaff uses a foreign key to reference a field in User; then if you delete a record from UserStaff that will be removed wihtout having any affect on the User table. The other way around will delete all records related to that record.
Short version: A field in UserStaff should reference a field in User with CASCADE

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

MySQL Error Code 1215: Cannot add foreign key Constraint on ALTER TABLE : Mysql

I want to add foreign key Constraint on my existing tables(type InnoDB)
,I have two tables listed below:
tbl_users : [ user_id(INT,AUTO_INCREMENT), user_name,--- etc]
tbl_users_meta : [ user_meta_id(INT,AUTO_INCREMENT), user_id(INT),--- etc]
I have already created index 'user_id' on 'tbl_users_meta' listed below :
Here is my Query but i am getting (MySQL Error Code 1215: ) each time.what is the problem i can getting it ?
ALTER TABLE `tbl_users_meta`
ADD CONSTRAINT `fk users user_id`
FOREIGN KEY (`user_id`) REFERENCES
`sanskrut`.`tbl_users`(`user_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
TRY with the same query you have writen with a small modification:
ALTER IGNORE TABLE `tbl_users_meta`
ADD CONSTRAINT `fk users user_id`
FOREIGN KEY (`user_id`) REFERENCES
`sanskrut`.`tbl_users`(`user_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
Hope it'll work
I can't see anything wrong with what you've written, so there must be something you haven't posted affecting the problem. For example, on MySQL version 5.5.44, I can successfully execute the following:
CREATE DATABASE sanskrut;
USE sanskrut;
CREATE TABLE tbl_users (user_id INT AUTO_INCREMENT PRIMARY KEY, user_name VARCHAR(50));
CREATE TABLE tbl_users_meta (user_meta_id INT AUTO_INCREMENT PRIMARY KEY, user_id INT);
CREATE INDEX user_id ON tbl_users_meta (user_id);
ALTER TABLE `tbl_users_meta`
ADD CONSTRAINT `fk users user_id`
FOREIGN KEY (`user_id`) REFERENCES
`sanskrut`.`tbl_users`(`user_id`)
ON DELETE NO ACTION ON UPDATE CASCADE;
...which finishes with your exact problem statement, copied and pasted, and works just fine.
I'd suspect, as I mentioned in the comments, that there's an index missing or possibly a datatype mismatch. You may find it helpful to add the output of:
DESC tbl_users;
DESC tbl_users_meta;
SHOW indexes FROM tbl_users;
SHOW indexes FROM tbl_users_meta;
...to your question.

On delete cascade is not working

I have two table: users and 'bills'. In bills as a foreign key to users.
I want to automatically delete rows from the bills table when I delete from the users table. For that I alter table with following query, still it doesn't delete entry from bills table.
My alter statement is:
ALTER TABLE bills
ADD CONSTRAINT fk_pid
FOREIGN KEY (pid)
REFERENCES users(id)
ON DELETE CASCADE
here pid is foreign key in bills table, whereas id primary key in users table
Please help me to resolve above issue, thank you in advance.
Use create instead of alter,Otherwise your syntax is ok
Create TABLE bills(
Your columns details
------
------
ADD CONSTRAINT fk_pid
FOREIGN KEY (pid)
REFERENCES users(id)
ON DELETE CASCADE
)
Try this..
If it's doesn't work then try for this thing as well.
if your both tables having mismatch primary key and foreign key problem then you cannot add Delete Cascade.For that you need to fix that key problem.like you don't have primary key value in your user table and you are using that same id in your bills table as a foreign key then you cannot add cascade in bills table.For that remove that key from bills table and then try your adding cascade script with Alter.I had same problem but i use this way and it worked.Hope it will work for you as well.Thanks
I think this solution for create can help you in figuring out what actually you are missing.
Go thru it and try customizing it as per your need, as you haven't provided enough detail
along with your question.
I suspect it has to do something with your create table statement
OR try this for ALTER1
OR ALTER2

On delete cascade - where I have to add it

I needed an example of cascade delete. My question is, where do I add it? In the table I create PK, or in other tables where this PK is sitting there as FK?
Can I use "alter table" to add "on delete cascade" to existing table? An example please?
#edit
MYSQL, using phpMyAdmin
#edit 2
Does it look good?
alter table wplaty
drop foreign key pesel,
add constraint pesel foreign key (pesel)
references baza_osob(pesel) on delete cascade on update restrict;
My parent table = baza_osob
My child table = wplaty
PK is pesel, FK is pesel as well.
#edit3
Got error:
#1025 - Error on rename of '.\projekt\wplaty' to '.\projekt#sql2-1300-6c' (errno: 152)
cascade directives go into the "child" tables, e.g.
create table parent (
id int primary key
)
create table child (
id int primary key
parent_id int,
foreign key (parent_id) references parent (id)
on delete cascade
)
Never tried doing an alter on a foreign key to change its on settings, but worst case, you simply drop the existing FK and redefine it with the new on settings in place.
You actually don't add the 'ON DELETE CASCADE' on a table. It's part (or not) of each Foreign Key definition.
You need to enable this option for the foreign key. If you did not add this option when you created foreign key, then you should recreate it.
alter table <table> drop foreign key <fk name>;
alter table <table> add constraint <fk name> foreign key (<column name>)
references <ref tble>(<ref column) on delete cascade on update restrict;
In one statement:
alter table <table>
drop foreign key <old fk name>,
add constraint <new fk name> foreign key (<column name>)
references <ref tble>(<ref column) on delete cascade on update restrict;

Categories