ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2019-05-28 02:03:08  阅读:375  来源: 互联网

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


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

但遇到这个问题,

ERROR 1064 (42000) at line 99: You have an error in your SQL syntax; 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)
)’ at line 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) 

标签:mysql,foreign-keys,create-table,self-reference,gtfs
来源: https://codeday.me/bug/20190528/1167579.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有