首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SQL中的多对多层次关系

SQL中的多对多层次关系
EN

Stack Overflow用户
提问于 2018-01-19 01:17:16
回答 1查看 33关注 0票数 0

我正在试图找出如何在数据库中存储分层数据,但我遇到了麻烦,因为数据似乎不适合简单的树层次结构。我在看市场指数和分指数,它们可以用多种不同的方式、多个不同的层次来划分。我试着用一个简单的例子来解释。

假设我们有一个代表整个世界的指数,世界上只有两个国家(美国和中国)。此外,股票只能分为两类(技术和保健)。这将使我有以下9个指数:

代码语言:javascript
运行
复制
|-------------------|---|
|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 |
|-------------------|---|

世界指数可以分为美国和中国,但也可以分为技术和卫生保健。此外,美国指数可分为美国技术和美国卫生保健,而美国保健也是保健的一个组成部分(与中国保健一起)。

我希望能够检索各种不同的索引分组方法。下面是一些示例:

  • 按国家分组:{ 1: 2,3}
  • 按扇区分组:{ 1: 4,5}
  • 按国家、部门分组:{ 1:[2: 6,7,3: 8,9] }
  • 按部门分组,国家:{ 1:[4: 6,8,5: 7,9] }

对于如何在关系表中表示这一点,有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2018-01-19 01:58:10

如果您只是想存储和检查索引/子索引、国家和部门之间的关系,那么一种解决方案涉及五个表:索引表、扇区表、扇区索引连接表、国家表和国家索引连接表。索引表可以保存对任何父索引(自连接)的引用。显然,这个模式对基数做了一些假设,您需要确认这些假设。木琴

代码语言:javascript
运行
复制
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));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48332769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档