如何在单个MySQL语句中添加列并使其成为外键? [英] How to add a column and make it a foreign key in single MySQL statement?

查看:76
本文介绍了如何在单个MySQL语句中添加列并使其成为外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在mysql中,我可以在同一条语句中添加列和外键吗?加上fk的正确语法是什么?

In mysql, can I add a column and foreign key in the same statement? And what is the proper syntax for adding the fk?

这是我的SQL:

ALTER TABLE database.table
 ADD COLUMN columnname INT DEFAULT(1),
 FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;

...以及随附的错误消息:

...and the accompanying error message:

您的SQL语法有错误;在第4行的"FOREIGN KEY(fk_name)参考引用reftable(refcolumn)ON DELETE CASCADE"附近使用正确的语法检查与您的MySQL服务器版本相对应的手册

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE' at line 4

推荐答案

尝试一下:

ALTER TABLE database.table
  ADD COLUMN columnname INT DEFAULT(1),
  ADD FOREIGN KEY fk_name(fk_column) REFERENCES reftable(refcolumn) ON DELETE CASCADE;

这篇关于如何在单个MySQL语句中添加列并使其成为外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆