【问题标题】:How do I create a table with self-referencing fields in MySQL?如何在 MySQL 中创建具有自引用字段的表?
【发布时间】:2016-06-08 13:47:57
【问题描述】:

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

但遇到问题,

第 99 行的 ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在 'FOREIGN KEY parent_station REFERENCES stop(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?

引起的

【问题讨论】:

    标签: mysql foreign-keys create-table self-reference gtfs


    【解决方案1】:

    我尝试在使用此命令创建表后添加外键并且它有效:

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

    【讨论】:

      【解决方案2】:

      这是一个简单的语法错误。试试这个:

      FOREIGN KEY (parent_station) REFERENCES stops(stop_id) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-15
        • 2014-08-12
        • 2011-02-27
        • 2011-11-23
        • 1970-01-01
        • 2015-11-19
        • 1970-01-01
        • 2021-02-05
        相关资源
        最近更新 更多