SQL Server:从两个表获取数据的高性能方法
我必须在父子关系 (1:n) 的两个表中搜索,但在结果集中我只需要父表的字段。做到这一点最有意义的方法是什么?是以下简化结构之一……
SELECT parent.fields FROM parent LEFT OUTER JOIN child ON [JoinExpr]
Where [ParentFilter] OR [ChildFilter] GROUP BY parent.fields
SELECT DISTINCT(parent.fields) FROM parent LEFT OUTER JOIN child ON [JoinExpr]
Where [ParentFilter] OR [ChildFilter]
SELECT parent.fields FROM parent Where [ParentFilter]
OR parent_id IN(SELECT parent_id FROM child WHERE [ChildFilter])
还是还有其他更好的可能性?数据将通过ado.net查询。
I have to search in two tables that are in a parent-child relation (1:n) but in the result set I only need fields of the parent table. What is the most meaningfull way to do this? Is it one of the following simplified constructions ...
SELECT parent.fields FROM parent LEFT OUTER JOIN child ON [JoinExpr]
Where [ParentFilter] OR [ChildFilter] GROUP BY parent.fields
SELECT DISTINCT(parent.fields) FROM parent LEFT OUTER JOIN child ON [JoinExpr]
Where [ParentFilter] OR [ChildFilter]
SELECT parent.fields FROM parent Where [ParentFilter]
OR parent_id IN(SELECT parent_id FROM child WHERE [ChildFilter])
... or are there other, better possibilities? The data will be queried by ado.net.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么你坚持使用外连接。根据您的描述,结果将来自父表,子表将仅用作限制的一部分。在这种情况下,您应该使用内部联接。如果子表在特定条件上不匹配,那么它不会显示在您的结果中。性能实际上取决于构成连接和过滤条件的字段。尝试确保连接(外键)中的字段已建立索引,并且在必要时过滤条件字段也已建立索引。不要在过滤条件中使用函数,例如 field1 >= DATEDIFF(???)。我忘记了 datediff 的确切语法。这意味着对完整数据集中的每一行计算 datediff。在这种情况下,子查询可能会很有用
Why are you insisting on using an outer join. From your description the results are going to come from the parent table and the child table will only be used as part of the restriction. In this case you should use an inner join. If the child table does not have a match on a specific criteria then it won't show in your results. The performance will really come down to the fields that make up the join and the filter criteria. Try to make sure that the fields in the join (foreign key) are indexed and where necessary the filter criteria fields are also indexed. Don't use functions in the filter criteria e.g. where field1 >= DATEDIFF(???). I forget the exact syntax for datediff. This will mean that datediff is evaluated for each row in the full set of data. In cases like this a sub-query can be useful