[英]How do I create a table with self-referencing fields in MySQL?
In GTFS, the field parent_station
is either from stop_id
(self-reference) or NULL
. 在GTFS中,字段
parent_station
来自stop_id
(自引用)或NULL
。 For instance (note that parent_station
might be NULL
), 例如(请注意,
parent_station
可能为NULL
),
SELECT stop_id, stop_name, parent_station FROM stops where stop_id='1970324837184617' OR parent_station='1970324837184617';
+------------------+----------------------+------------------+
| stop_id | stop_name | parent_station |
+------------------+----------------------+------------------+
| 1970324837184617 | Saint Agne-SNCF | |
| 3377699720880648 | Saint Agne-SNCF | 1970324837184617 |
| 3377699720880649 | Saint Agne-SNCF | 1970324837184617 |
| 3377699722011100 | Saint Agne-SNCF | 1970324837184617 |
| 3377699722011101 | Saint Agne-SNCF | 1970324837184617 |
| 3377699722914835 | Saint Agne Gare SNCF | 1970324837184617 |
+------------------+----------------------+------------------+
6 rows in set (0,01 sec)
I create a self-referencing table with: 我创建了一个自引用表:
CREATE TABLE `stops` (
stop_id VARCHAR(255) NOT NULL PRIMARY KEY,
stop_code VARCHAR(255),
stop_name VARCHAR(255),
stop_desc VARCHAR(255),
stop_lat DECIMAL(8,6),
stop_lon DECIMAL(8,6),
location_type INT(2),
parent_station VARCHAR(255),
-- the field `parent_station` might be blank (NULL)
FOREIGN KEY parent_station REFERENCES stops(stop_id) -- self-referential table fields
);
but encounter the issue, 但遇到这个问题,
ERROR 1064 (42000) at line 99: You have an error in your SQL syntax;
错误1064(42000)在第99行:您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY parent_station REFERENCES stops(stop_id)
查看与您的MySQL服务器版本对应的手册,以便在'FOREIGN KEY附近使用正确的语法.parent_station REFERENCES停止(stop_id)
)' at line 11)'在第11行
With the help of @Awita, I correct the syntax and the table is created successfully. 在@Awita的帮助下,我更正了语法并成功创建了表。
FOREIGN KEY (parent_station) REFERENCES stops(stop_id)
But a new issue occurs while loading local data. 但是在加载本地数据时会出现一个新问题。
LOAD DATA LOCAL INFILE 'stops.txt' INTO TABLE stops FIELDS TERMINATED BY ',' IGNORE 1 LINES;
The error: 错误:
ERROR 1452 (23000) at line 140: Cannot add or update a child row: a foreign key constraint fails (`paris_gtfs`.`stops`, CONSTRAINT `stops_ibfk_1` FOREIGN KEY (`parent_station`) REFERENCES `stops` (`stop_id`))
This issue is caused by NULL parent_station
? 此问题是由NULL
parent_station
引起的?
It's a simple syntax error. 这是一个简单的语法错误。 Try this:
试试这个:
FOREIGN KEY (parent_station) REFERENCES stops(stop_id)
I tried to add the foreign key after the table has been created with this command and it works: 我尝试使用此命令创建表后添加外键,它可以正常工作:
ALTER TABLE stops
ADD FOREIGN KEY (parent_station)
REFERENCES stops(stop_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.