0

我在我的一个 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

4

3 回答 3

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';
于 2013-06-21T14:04:52.127 回答
1

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

随着您了解如何进行连接以及避免子查询和相关子查询如何影响您的执行计划,您将对 MSSQL 有更好的基本理解,并能够在未来更好地编写代码。

于 2013-06-21T14:22:15.087 回答
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
于 2013-06-21T14:12:45.380 回答