我正计划建立一个庞大的数据库。我以前就有过一个客户,他的数据库超过100万行。假设我们有一个100行的表a,有多个250行的表。
我想知道哪种方法通常更快(我知道这取决于很多事情):
基于IDs将小表连接到大表
在大表中包含小表值
例如:
第一个选项:
id | data1 | data2 | data3 | table1_foreign_key | table2_foreign_key | table3_foreign_key
--------------------------------------------------------------------------------------------------------------
1 | test | test | test | 12 | 34 | 22
2 | test | test | test | 34 | 67 | 63
3 | test | test | test | 43 | 34 | 18
4 | test | test | test | 23 | 21 | 22
5 | test | test | test | 22 | 34 | 22
6 | test | test | test | 22 | 34 | 13
7 | test | test | test | 23 | 54 | 12
8 | test | test | test | 11 | 57 | 43
9 | test | test | test | 3 | 34 | 22
在这里,我会根据id将这些小表连接到大表。例如,我会在这里储存城市、国家、设备等。
第二种选择:
id | data1 | data2 | data3 | table1_foreign_key | table2_foreign_key | table3_foreign_key
--------------------------------------------------------------------------------------------------------------
1 | test | test | test | Oklahoma | sample_text | sample_text
2 | test | test | test | New York | sample_text | sample_text
3 | test | test | test | New York | sample_text | sample_text
4 | test | test | test | New York | sample_text | sample_text
5 | test | test | test | Washington | sample_text | sample_text
6 | test | test | test | Mitchigan | sample_text | sample_text
7 | test | test | test | Oklahoma | sample_text | sample_text
8 | test | test | test | Kansas | sample_text | sample_text
9 | test | test | test | Dallas | sample_text | sample_text
在第二个选项中,没有连接,但是数据将包含在主大表中。每列的预期数据大小大约为2-20个字符。
问题:
考虑到我们拥有相同的环境和合适的索引,上述选项中的哪一个可以更快?这里建议采用哪种方法?(我的客户希望在此数据库和表中存储单击和单击数据。)
最佳答案
既然是“一对多”关系,我会把它们存储在单独的表中。SQL server查询优化器(在引擎盖下)将能够足够快地解析250条记录,不必担心。另外,根据小表中的值的长度,您将通过不存储它们数亿次来节省存储空间。但是,如果报告性能是最重要的,您可以选择将它们存储在一个“扁平”的表中,就像数据仓库结构一样,而不使用连接。这肯定会更快,但您将牺牲存储空间和结构良好的关系数据库。
所有这些都表明,我会选择1。但是,您应该能够轻松地将数据存储在一个新表中,并使用选项2格式(针对这两种格式进行查询),然后为自己衡量性能。我想这不会有太大的区别,特别是考虑到你们小桌子的容量。