Problem creating foreign keys in mySql

点点圈 提交于 2019-12-23 02:54:15

问题


I created a foreign key in my sql by the following statemnt..

ALTER TABLE `users` ADD FOREIGN KEY ( `id`) 
REFERENCES `user_login` (`user_id`) 
ON DELETE CASCADE ;

The creation appears to succeed then after that I execute a delete statement

DELETE From user_login WHERE user_id = 1576;

yet in users the row still exists that is referencing that. I open up the mysql workbench and it doesn't show any signs that the foreign key was created. Does anyone know why this would be? Or what I am doing wrong? It is a one-to-one relationship in the two tables.


回答1:


The table may be in MyISAM format, which does not support foreign keys.

Try converting it to InnoDB first:

alter table users engine=InnoDB;



回答2:


You have to also make sure that both users.id and user_login.user_id have an index each.




回答3:


Copy and paste this code in your Mysql script editor and run. You will have two tables categories and products these tables having cat_id as foreign key.

CREATE DATABASE IF NOT EXISTS dbdemo;

USE dbdemo;

CREATE TABLE categories(
   cat_id int not null auto_increment primary key,
   cat_name varchar(255) not null,
   cat_description text
) ENGINE=InnoDB;

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;


来源:https://stackoverflow.com/questions/4769357/problem-creating-foreign-keys-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!