1

嗨,我正在一个项目中工作,我必须用父子关系保存数据。

数据结构是这样的:

flight_id     child_id      Flight_name 

1               1           E213    

2               2           E333

3               2           E444  

航班 1 没有child_id所以它的父 id 替换它,航班 2 有两个所以我必须child_id在每个中放置父 id。child_id

知道我该怎么做吗?

4

2 回答 2

1

Parent-child relationships are usually modeled the other way around: the child belongs to a parent. Think about it, a child can only have one parent, that's easy to model; but a parent with many child ids is pretty hard to model.

Additionally you can use Nested Sets a.k.a. MPTT to make querying for children/parents easier.

See http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ and http://en.wikipedia.org/wiki/MPTT.

于 2012-07-04T09:56:38.273 回答
0

Normally you won't store all the child ID's, but the parent ID's:

CREATE TABLE `flight` (
    `id` int(11) NOT NULL,
    `parent` int(11) DEFAULT NULL,
    `flight_name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`),
    FOREIGN KEY (`parent`) REFERENCES `flight` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Your data would look like:

id     parent    flight_name 
1      NULL      E213    
2      NULL      E333
3      2         E444  
4      2         E555  
5      2         E666  
于 2012-07-04T09:57:35.297 回答