2011-12-21 98 views
0

在一个表中,有另一个表中有两个外键。SQL内部联接问题

第一个表格是文档而另一个表格是常见的

我当前的代码,

SELECT a.* FROM documents AS a INNER JOIN common AS c ON a.docId = c.id INNER JOIN common as cc ON a.statusId = cc.id 

什么是加入了更好的性能的最佳方式?

谢谢。

+0

还有,如果你的查询产生你想要的结果没有更好的办法。注意:使用'select *'不太好。更好地指定你实际需要的字段。 http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful – 2011-12-21 07:26:55

+0

感谢您的信息。 – kevin 2011-12-21 07:47:56

回答

2

你的SQL看起来很好。确保你的fk栏有索引,你应该很好走。你关心的原因究竟是什么?

+0

使用索引的原因是什么?我只是好奇,如果有更好的方法。 – kevin 2011-12-21 07:43:19

+0

indices =索引的复数 – 2011-12-21 07:43:46

+0

是的,我对索引不太了解。那些索引应该用于文档表?它会更快? – kevin 2011-12-21 07:47:19

1

为什么你加入公共表两次,甚至不选择任何列? 如果您使用join用于过滤你可以尝试做这样的:

SELECT a.* 
FROM documents AS a 
WHERE (SELECT COUNT(*) FROM common 
     WHERE a.docId = id OR a.statusId = id)>0 

然后您确保ID,和的docId是statusId索引。

如果你只是忘了添加c和cc表到你的列选择你很好,只是加快设置索引,如果你还没有。

+0

我忘记选择公共表中的列。 它应该是** a。*,c.Name,cc.Name ** – kevin 2011-12-21 07:46:00

1

选择字段不使用select *这可以增加在服务器和客户端的数据流量性能和设置键和索引的表

Select a.fieldone, a.fieldtwo FROM documents AS a 
INNER JOIN common AS c ON a.docId = c.id 
INNER JOIN common as cc ON a.statusId = cc.id 
+0

感谢您的信息。 – kevin 2011-12-21 07:47:46

1

基本连接策略遵循

1) Index the joined fields. 
2) Ensure that statistics are upto date, this way SQL wont recalculate plan and will used the cached plan 
3) Join from the smaller table to the bigger one, help sql server 
choose the best plan 
4) Read the Query Analyser Plan, if you see a Hash Join being performed on two large tables then add a covering index to make it choose a nested loop join which is better 
5) If a small table is joined to a large table a Hash join is so much 
better. 
6) Avoid bookmark lookups. See this for more info http://www.sqlservercentral.com/articles/Performance+Tuning/bookmarklookups/1899/ 
+0

感谢您的信息。什么是统计数据? 如何阅读查询分析器计划?和什么是哈希加入? 对不起,我的无知。我不擅长SQL。 – kevin 2011-12-21 08:24:57

+1

统计信息是DB统计信息,由sqlserver用于索引的新鲜度。您可以在查询:菜单下的sqlserver中看到“实际执行计划”。本文是关于散列连接的基本解释http://msdn.microsoft.com/en-us/library/aa178403(v=SQL.80)。aspx,你不必知道它,但它调整查询时很有用 – lloydom 2011-12-21 08:26:06

+0

再次感谢! – kevin 2011-12-21 08:32:12

1

总是有使用SQL编写任何查询的方法不止一种,为测试性能测试至少两个候选查询可能是一个好主意。影响性能的因素很多,其中最重要的就是您正在使用的SQL产品。

注意到,这两个连接到commonsemijoins这里有一个建议的替代:

SELECT * 
    FROM documents AS a 
WHERE EXISTS (
       SELECT * 
       FROM common AS c 
       WHERE a.docId = c.id 
      ) 
     AND EXISTS (
        SELECT * 
        FROM common AS cc 
        WHERE a.statusId = cc.id 
       );