我正在使用以下 mariadb 代码创建一个名为 user 的表,并带有一些外键
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `shipping_address` int(11) NULL,
ADD COLUMN IF NOT EXISTS `billing_address` int(11) NULL,
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_2` FOREIGN KEY (`shipping_address`) REFERENCES `user_address` (`id`),
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_3` FOREIGN KEY (`billing_address`) REFERENCES `user_address` (`id`);
我认为这段代码是正确的,但仍然会产生以下错误
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FOREIGN KEY (`shipping_address`) REFERENCES `user_address` (`id`),
ADD CON...' at line
这段代码真的正确吗?如果不是那么我该如何修复它?该代码的正确变体是什么?
正如 mariadb(不是 mysql!)关于 alter table 的文档所示,
if not exists
子句出现在 after foreign key
:
ADD [CONSTRAINT [symbol]]
FOREIGN KEY [IF NOT EXISTS] [index_name] (index_col_name,...)
reference_definition
所以,你的更改表应该看起来像这样
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `shipping_address` int(11) NULL,
ADD COLUMN IF NOT EXISTS `billing_address` int(11) NULL,
ADD CONSTRAINT `user_ibfk_2` FOREIGN KEY IF NOT EXISTS (`shipping_address`) REFERENCES `user_address` (`id`),
ADD CONSTRAINT `user_ibfk_3` FOREIGN KEY IF NOT EXISTS (`billing_address`) REFERENCES `user_address` (`id`);