我正在试图找出如何在数据库中存储分层数据,但我遇到了麻烦,因为数据似乎不适合简单的树层次结构。我在看市场指数和分指数,它们可以用多种不同的方式、多个不同的层次来划分。我试着用一个简单的例子来解释。
假设我们有一个代表整个世界的指数,世界上只有两个国家(美国和中国)。此外,股票只能分为两类(技术和保健)。这将使我有以下9个指数:
|-------------------|---|
|Index |ID |
|-------------------|---|
| World | 1 |
| USA | 2 |
| China | 3 |
| Technology | 4 |
| Health Care | 5 |
| USA Technology | 6 |
| USA Health Care | 7 |
| China Technology | 8 |
| China Health Care | 9 |
|-------------------|---|
世界指数可以分为美国和中国,但也可以分为技术和卫生保健。此外,美国指数可分为美国技术和美国卫生保健,而美国保健也是保健的一个组成部分(与中国保健一起)。
我希望能够检索各种不同的索引分组方法。下面是一些示例:
对于如何在关系表中表示这一点,有什么建议吗?
发布于 2018-01-19 01:58:10
如果您只是想存储和检查索引/子索引、国家和部门之间的关系,那么一种解决方案涉及五个表:索引表、扇区表、扇区索引连接表、国家表和国家索引连接表。索引表可以保存对任何父索引(自连接)的引用。显然,这个模式对基数做了一些假设,您需要确认这些假设。木琴
create table indices (indexid int not null primary key, name nvarchar(100), parentIndex int null,
foreign key (parentindex) references indices(indexid));
create table sectors (sectorid int not null primary key, name nvarchar(200));
create table countries (countryid int not null primary key, name nvarchar(200));
create table indices_join_sectors (sectorid int not null, indexid int not null,
foreign key (sectorid) references sectors(sectorid),
foreign key (indexid) references indices(indexid));
create table indices_join_countries (countryid int not null, indexid int not null,
foreign key (countryid) references countries(countryid),
foreign key (indexid) references indices(indexid));
https://stackoverflow.com/questions/48332769
复制相似问题