SQL内部连接问题

时间:2011-12-21 07:22:02

标签: 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

什么是加入更好表现的最好方式?

感谢。

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

为什么要加入公共表两次,甚至不选择任何列? 如果您使用联接进行过滤,可以尝试这样做:

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表添加到列中,那么选择就可以了,如果您还没有加快设置索引的速度。

答案 2 :(得分: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

答案 3 :(得分: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/

答案 4 :(得分:1)

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

注意到common的两个联接是semijoins,这是一个建议的选择:

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
                  );