mySQL创建外键

时间:2016-07-30 16:33:51

标签: mysql foreign-keys

ALL,

igor@IgorDellGentoo ~ $ isql myodbc-5.2-test root wasqra
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL> use draft;  
SQLRowCount returns 0
SQL> ALTER TABLE owners ADD FOREIGN KEY id REFERENCES leagues(id);
[ISQL]ERROR: Could not SQLExecute
SQL> 

我做错了什么?

另外,由于某些原因,我在创建表时无法通过mySQL-Workbench创建外键。

没有“添加”按钮或“+”符号来添加此约束。右键单击没有任何反应。

有人可以指出我正确的方向吗? 我在Gentoo Linux上有Workbench版本6.3.4.0。

SQL> show tables;
+-----------------------------------------------------------------+
| Tables_in_draft                                                 |
+-----------------------------------------------------------------+
| leagues                                                         |
| owners                                                          |
+-----------------------------------------------------------------+
SQLRowCount returns 2
2 rows fetched
SQL> SELECT * FROM leagues;
+-----------+-----------------------------------------------------------------------------------------------------+-----------+------------+-----------+-----------+-----------+-------------+
| id        | name                                                                                                | drafttype | scoringtype| roundvalue| leaguetype| salary    | benchplayers|
+-----------+-----------------------------------------------------------------------------------------------------+-----------+------------+-----------+-----------+-----------+-------------+
+-----------+-----------------------------------------------------------------------------------------------------+-----------+------------+-----------+-----------+-----------+-------------+

1 个答案:

答案 0 :(得分:2)

似乎你使用id作为外键而不是使用正确的列

ALTER TABLE owners 
ADD COLUMN FOREIGNID INT NOT NULL;

 ALTER TABLE owners 
 ADD FOREIGN KEY (FOREIGNID) REFERENCES leagues(ID);