sql – 如何避免许多数据库往返和大量无关数据?
我曾经使用各种应用程序,并多次遇到过这种情况.到目前为止,我还没有想出什么是最好的方法.
这是场景: >我有桌面或网络应用程序 GeneralDetails表: | DocumentID | DateCreated | Owner | | 1 | 07/07/07 | Naruto | | 2 | 08/08/08 | Goku | | 3 | 09/09/09 | Taguro | ItemDetails表 | DocumentID | Item | Quantity | | 1 | Marbles | 20 | | 1 | Cards | 56 | | 2 | Yo-yo | 1 | | 2 | Chess board | 3 | | 2 | GI Joe | 12 | | 3 | Rubber Duck | 1 | 如您所见,表格具有一对多的关系.现在,为了检索所有文件及其各自的项目,我总是做两个中的任何一个: 方法1 – 许多往返(伪代码): Documents = GetFromDB("select DocumentID,Owner " + "from GeneralDetails") For Each Document in Documents { Display(Document["CreatedBy"]) DocumentItems = GetFromDB("select Item,Quantity " + "from ItemDetails " + "where DocumentID = " + Document["DocumentID"] + "") For Each DocumentItem in DocumentItems { Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"]) } } 方法2 – 许多不相关的数据(伪代码): DocumentsAndItems = GetFromDB("select g.DocumentID,g.Owner,i.Item,i.Quantity " + "from GeneralDetails as g " + "inner join ItemDetails as i " + "on g.DocumentID = i.DocumentID") //Display... 我在大学期间使用第一种方法进行桌面应用时,性能并不差,所以我意识到它没问题. 直到有一天,我看到一篇文章“让网络变得更快”,它说许多往返数据库的往返很糟糕;所以从那时起我就使用了第二种方法. 在第二种方法中,我通过使用内部联接来一次检索第一个和第二个表来避免往返,但它会产生不必要的或冗余的数据.查看结果集. | DocumentID | Owner | Item | Quantity | | 1 | Naruto | Marbles | 20 | | 1 | Naruto | Cards | 56 | | 2 | Goku | Yo-yo | 1 | | 2 | Goku | Chess board | 3 | | 2 | Goku | GI Joe | 12 | | 3 | Taguro | Rubber Duck | 1 | 结果集具有冗余DocumentID和Owner.它看起来像一个非标准化的数据库. 现在,问题是,如何避免往返,同时避免冗余数据? 解决方法ActiveRecord和其他ORM使用的方法是选择第一个表,将ID一起批处理,然后在第二个选择的IN子句中使用这些ID.
好处: >没有冗余数据 缺点: >两个问题 一般而言,第一种方法被称为“N 1查询问题”,并且该解决方案被称为“急切加载”.我倾向于认为你的“方法2”更好,因为数据库的延迟通常胜过冗余数据的大小超过数据传输速率,但YRMV.与软件中的几乎所有内容一样,这是一种权衡. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |