我打算创建一个包含两列(bus_id,bus_passengers)的表。 bus_id将成为主键,并且将是来自另一个创建的表的外键,该表称为“beacap_locationLog”,列为node_id。
这是我写的代码(mySQL):
CREATE TABLE Bus(
bus_id INT (10) UNSIGNED NOT NULL,
bus_passengers INT,
PRIMARY KEY (bus_id),
FOREIGN KEY (bus_id) REFERENCES beacap_locationLog(node_id)
);
它给了我这个错误:
#1005 - Can't create table 'pei.Bus' (errno: 150)
我不知道问题是什么。
答案 0 :(得分:0)
不能拥有主+外键!具有相同名称的列
Shoul会是这样的!
- 我已经添加了一个新专栏!!
CREATE TABLE Bus(
bus_id INT (10) UNSIGNED NOT NULL,
bus_passengers INT,
node_id_fk int,
PRIMARY KEY (bus_id),
FOREIGN KEY (node_id_fk) REFERENCES beacap_locationLog(node_id)
);
好的,请参阅完整示例:
mysql> create table beacap_locationLog(
-> node_id int
-> );
Query OK, 0 rows affected (0.26 sec)
mysql> CREATE TABLE Bus(
-> bus_id INT (10) UNSIGNED NOT NULL,
-> bus_passengers INT,
-> node_id_fk int,
-> PRIMARY KEY (bus_id),
-> FOREIGN KEY (node_id_fk) REFERENCES beacap_locationLog(node_id)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql> desc beacap_locationLog;
+---------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| node_id | int(11) | YES | | NULL | |
+---------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
mysql> desc Bus;
+----------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------+------+-----+---------+-------+
| bus_id | int(10) unsigned | NO | PRI | NULL | |
| bus_passengers | int(11) | YES | | NULL | |
| node_id_fk | int(11) | YES | MUL | NULL | |
+----------------+------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql>
TBL总线定义
mysql> show create table Bus\G
Table: Bus
Create Table: CREATE TABLE Bus (
bus_id int(10) unsigned NOT NULL,
bus_passengers int(11) default NULL,
node_id_fk int(11) default NULL,
PRIMARY KEY (bus_id),
KEY node_id_fk (node_id_fk)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.01 sec)