提高查询速度
好的,我有表格:
ID Name Description Picture
1 Alex Alex desc.. 2
2 Maria NULL 3
3 John John desc.. NULL
表格图片有 ID 和 varbinary 图像。
我需要选择:如果描述存在,则描述,否则图片 我这样做:
select Id,
Name,
Case when Description is null then pic.Image else Description
from person per join picture pic on per.Picture = pic.Id
所以,如果描述不为空,看起来像是不必要的连接。 无论如何。关于改进这个简单查询有什么建议吗?另外,有哪些易于使用的好工具来比较两个版本的查询的性能?
Okay I have table:
ID Name Description Picture
1 Alex Alex desc.. 2
2 Maria NULL 3
3 John John desc.. NULL
table picture has ID and varbinary image.
I need to select: If description exists, then description, else picture
I do this:
select Id,
Name,
Case when Description is null then pic.Image else Description
from person per join picture pic on per.Picture = pic.Id
So, looks like unnecessary join if description is not null.
Anyways. any suggestions on improving this simple query? also, What are good easy to use tools for performance comparison between two version of queries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,没有办法在单个查询中进行条件连接。我可能会将您的内容重写为:
我不确定性能比较如何,但看起来更干净一些。
就比较查询而言,我建议查看两者的执行计划,看看其中一个是否正在进行任何扫描。以下是有关使用执行计划进行性能调整的一些信息:
您还可以使用 Database Tuning Advisor 作为检查是否拥有必要索引的快速方法。
请注意不要花费太多时间进行优化。虽然关注当前性能和数据库增长时的性能固然很好,但很容易在这方面花费大量时间而得不到太多回报。如果您有良好的数据库结构和编写良好的查询,那么未来的优化应该不会太痛苦。
As far as I know there is no way to conditionally join within a single query. I would probably rewrite what you have as:
I'm not sure how the performance compares, but it seems a little cleaner.
As far as comparing queries goes, I would recommend looking at the execution plan for both and seeing if either are doing any scans. Here is some info on using execution plans for performance tuning:
You can also use the Database Tuning Advisor as a quick way to check to see if you have the necessary indexes.
Be careful to not spend too much time over optimizing either. While it's good to keep an eye on both current performance and performance as your database grows, it's easy to spend a lot of time on this without getting too much in return. If you have a good database structure and well written queries, then future optimizations shouldn't be too much of a pain.
但是如果描述不为空,则连接是必要的......这就是您的代码应该做的对吗?
您可以通过用一对“select getdate()”语句包装查询并进行数学计算(或编写 SQL 来为您进行数学计算)来粗略计算查询的时间。
But the join IS necessary if description isn't null.... and that's what your code is supposed to do right?
You can roughly time your queries by wrapping them with a pair of 'select getdate()' statements and doing the math (or write the SQL to do the math for you).
您也可以这样做:
不确定性能如何,但您只在需要时才进行连接,但代价是使用 UNION。 Union All 将消除对不同行进行排序的需要,这应该有助于提高性能。
You could also do something like this:
Not sure how performance would be, but you are only doing the join if needed, but at the cost of a UNION. Union All will eliminate the need for sorting out distinct rows, which should help performance.