如何改进此查询

时间:2013-06-21 13:53:01

标签: sql-server-2008 tsql

我在我的一个PHP应用程序中使用了这个查询:

SELECT DictSchemeName.schemeName, DictTableName.tableName 
FROM DictSchemeName, DictTableName 
WHERE DictSchemeName.Id = (SELECT  schemeName 
                           FROM ServiceSublayer 
                           WHERE sId = 3
                            AND ServiceId = (SELECT Id 
                                               FROM Service 
                                               WHERE applicationId = 'prga'))
  AND DictTableName.Id = (SELECT tableName
                          FROM ServiceSublayer
                          WHERE sId = 3 
                            AND ServiceId =(SELECT Id 
                                            FROM Service 
                                            WHERE applicationId = 'prga'));

你可以看到我将两次几乎相同的查询加倍(DictSchemeName和DictTableName),我开始学习SQL,如果有人可以帮助我,我会很高兴。

我使用的是MS SQL SERVER 2008

3 个答案:

答案 0 :(得分:6)

您应该可以加入表格:

select ds.schemeName,
  dt.tableName
from
(
  select schemeName, tableName
  from ServiceSublayer
  where sId = 3
    and ServiceId = (SELECT Id 
                     FROM Service 
                     WHERE applicationId = 'prga')
) s
inner join DictSchemeName ds
  on s.schemeName = ds.id
inner join DictTableName dt
  on s.tableName = dt.id;

甚至更进一步:

select ds.schemeName,
  dt.tableName
from ServiceSublayer ss
inner join Service s
  on ss.serviceId = s.id
inner join DictSchemeName ds
  on ss.schemeName = ds.id
inner join DictTableName dt
  on ss.tableName = dt.id
where ss.sId = 3
 and s.applicationId = 'prga';

答案 1 :(得分:1)

在分析每个查询时使用“包含实际执行计划”选项。有了它,您将能够看到您实际上如何改进每个查询。以下是介绍如何阅读查询计划的许多文章之一,http://www.mssqltips.com/sqlservertip/1630/how-to-use-a-sql-server-plan-guide-to-tune-queries/

当您继续执行连接以及避免子查询和相关子查询如何影响您的执行计划时,您将获得对MSSQL更好的基础理解,并且能够在将来更好地编写代码。

答案 2 :(得分:0)

将您的选择分解为单独的陈述......

DECLARE @ServiceId INT
DECLARE @schemeName VARCHAR
DECLARE @tableName VARCHAR

SELECT @ServiceId = Id 
FROM Service
WHERE applicationId = 'prga'

SELECT @schemeName=schemeName,@tableName=tableName
FROM ServiceSublayer 
WHERE ServiceId = @ServiceId AND sId = 3

SELECT DictSchemeName.schemeName, DictTableName.tableName 
FROM DictSchemeName, DictTableName 
WHERE DictSchemeName.Id = @schemeName
AND DictTableName.Id = @tableName