簡體   English   中英

如何在MySQL中創建具有自引用字段的表?

[英]How do I create a table with self-referencing fields in MySQL?

在GTFS中,字段parent_station來自stop_id (自引用)或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)

我創建了一個自引用表:

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
);

但遇到這個問題,

錯誤1064(42000)在第99行:您的SQL語法有錯誤; 查看與您的MySQL服務器版本對應的手冊,以便在'FOREIGN KEY附近使用正確的語法.parent_station REFERENCES停止(stop_id)
)'在第11行


在@Awita的幫助下,我更正了語法並成功創建了表。

FOREIGN KEY (parent_station) REFERENCES stops(stop_id) 

但是在加載本地數據時會出現一個新問題。

LOAD DATA LOCAL INFILE 'stops.txt' INTO TABLE stops FIELDS TERMINATED BY ',' IGNORE 1 LINES;

錯誤:

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`))

此問題是由NULL parent_station引起的?

這是一個簡單的語法錯誤。 試試這個:

FOREIGN KEY (parent_station) REFERENCES stops(stop_id) 

我嘗試使用此命令創建表后添加外鍵,它可以正常工作:

ALTER TABLE stops
ADD FOREIGN KEY (parent_station)
REFERENCES stops(stop_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM