mysql - cannot drop a foreign key in mySQL
问题描述
It's a common example between Persons and Orders. I just copied it from Internet as a test.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID) );
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(ID)
);
Till now it's all successful. But how can I drop the Foreign Key PersonID?
I tried this.
ALTER TABLE Orders
DROP FOREIGN KEY PersonID;
MySQL said:
1091 - Can't DROP 'PersonID'; check that column/key exists
解决方案
使用以下语句识别约束的名称:
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = 'Orders'
AND COLUMN_NAME = 'PersonID';
CONSTRAINT_NAME
在你的ALTER TABLE
陈述中使用结果。例如:
ALTER TABLE Orders
DROP FOREIGN KEY `myconstraint`;
答案来自MySQL 参考手册
推荐阅读
- email - Google Apps 脚本:无法使用 createEvent() 发送电子邮件
- sql - 窗口函数:仅对另一列中的不同值求和
- java - 如何配置 spring 应用程序以在 aws 上使用 IAM 角色(在 AWS ECS 内运行)和在 dev env 上使用凭证?
- php - 如何使用 codeigniter 查询生成器编写“ORDER BY NULL”
- build - 发布流水线设计理念
- c++ - 为什么以下成员初始化程序在 C++ 中不起作用
- javascript - 如何使用 AJAX 请求从本地路径和 JSON 文件获取照片。之后将其附加到 html 标签
- jquery - 使用 jQuery 获取两个 H2 之间的所有 H3
- vue.js - Vuejs 不适用于动态数组,但可以完美地与静态数组一起使用
- tensorflow - 如何在预加载的网络上添加另一层?