2015-04-02 57 views
2
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的自動忽略上表創建

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

MySQL的解析,但忽略「內聯參考Specifications」(如在SQL標準中定義的),其中的參考文獻中被定義爲列說明書的一部分。只有在指定爲單獨的FOREIGN KEY規範的一部分時,MySQL才接受REFERENCES子句。

你可以去here多看看自己......

+1

你參照的是澄清自己的方式頁面。我仍然不明白的部分是爲什麼它「解析但忽略內聯REFERENCES規範」?它解析但忽略了什麼? – 2015-04-02 23:47:46

+0

'定義在SQL標準中'......也許你應該看一下SQL標準,我相信他們把那個放在文檔中是有原因的。 – BK435 2015-04-03 00:00:09