MySql默默地忽略表创建时的“references”关键字

时间:2015-04-02 23:33:15

标签: mysql foreign-keys

mysql> create database test;
Query OK, 1 row affected (0.01 sec)

mysql> use test;
Database changed
mysql> create table one (id int not null primary key);
Query OK, 0 rows affected (0.03 sec)

mysql> -- here is the problem
mysql> create table two (oneid int not null references one(id));
Query OK, 0 rows affected (0.02 sec)

mysql> -- here are the first signs of issues!!!!
mysql> show create table two;
+-------+----------------------------------------------------------------------------------------+
| Table | Create Table                                                                           |
+-------+----------------------------------------------------------------------------------------+
| two   | CREATE TABLE `two` (
  `oneid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> -- here is the issue: an insert with no reference 
mysql> insert into two values (-12);
Query OK, 1 row affected (0.01 sec)

mysql> select * from two;
+-------+
| oneid |
+-------+
|   -12 |
+-------+
1 row in set (0.00 sec)
mysql> -- if you want to know:
mysql> SHOW Variables WHERE Variable_name='foreign_key_checks';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| foreign_key_checks | ON    |
+--------------------+-------+
1 row in set (0.00 sec)

经过我的研究,这里唯一的问题是:为什么MySql因为无效的语法而不拒绝表二创建,而是默认创建没有外键引用的表?
为了完整起见,这里是MySql的正确语法。

mysql> create table three(oneid int not null, CONSTRAINT whatEverName FOREIGN KEY (oneid) REFERENCES one(id));
Query OK, 0 rows affected (0.04 sec)

1 个答案:

答案 0 :(得分:1)

MySQL解析但忽略“内联REFERENCES规范”(在SQL标准中定义),其中引用被定义为列规范的一部分。 MySQL仅在指定为单独的FOREIGN KEY规范的一部分时才接受REFERENCES子句。

你可以去here并自己阅读更多...