更简单的SQL语法?哪种语法更好?

时间:2012-01-18 02:32:34

标签: sql

我有以下sql语法。这很好但我想知道是否有一种方法可以更简单地编写这种语法,因为MAX(ra0.DescPriority)使用相同的表连接。

SELECT DISTINCT Items_1.ImageID, Items_1.SubcategoryID2, Items_1.AddDate,
                                 (SELECT        MAX(ra0.DescPriority) AS Expr1
                                   FROM            Items INNER JOIN
                                                             Attribs AS ra0 ON Items.ImageID = ra0.ImageID) AS Pri
    FROM            Items AS Items_1 INNER JOIN
                             Attribs AS ra0 ON Items_1.ImageID = ra0.ImageID LEFT OUTER JOIN
                             v_DisplayStockPrice AS v_DisplayStockPrice_1 ON Items_1.ImageID = v_DisplayStockPrice_1.ImageID INNER JOIN
                             Attribs AS ra1 ON ra0.ImageID = ra1.ImageID
    WHERE        (Items_1.deleted NOT IN (1, 2)) AND (Items_1.SubcategoryID2 = 'ORD')
    ORDER BY Pri, Items_1.AddDate DESC

所以我提出了这种语法。

SELECT DISTINCT Items_1.ImageID, Items_1.SubcategoryID2, Items_1.AddDate, MAX(ra0.DescPriority) AS Pri
FROM            Items AS Items_1 INNER JOIN
                         Attribs AS ra0 ON Items_1.ImageID = ra0.ImageID LEFT OUTER JOIN
                         v_DisplayStockPrice AS v_DisplayStockPrice_1 ON Items_1.ImageID = v_DisplayStockPrice_1.ImageID INNER JOIN
                         Attribs AS ra1 ON ra0.ImageID = ra1.ImageID
WHERE        (Items_1.deleted NOT IN (1, 2)) AND (Items_1.SubcategoryID2 = 'ORD')
GROUP BY Items_1.ImageID, Items_1.SubcategoryID2, Items_1.AddDate
ORDER BY Pri, Items_1.AddDate DESC

哪种SQL语法更好?或者有更好的方法来编写此查询吗?

2 个答案:

答案 0 :(得分:1)

第二个看起来更好,可能表现更好,但实际上你应该使用查询分析器。它会告诉你哪个更好: http://msdn.microsoft.com/en-us/library/aa216945(v=sql.80).aspx

  

调试查询性能问题。 (显示执行计划,显示服务器跟踪,显示客户端统计信息,索引优化向导)

以下是如何使用查询执行计划的说明: http://www.sql-server-performance.com/2006/query-execution-plan-analysis/

答案 1 :(得分:0)

我使用Sql Prompt让你的查询看起来更漂亮。请注意,您的第三个连接没有做任何事情,INNER JOIN,OUTER JOIN,INNER JOIN的模式不正确,从不使用它。

SELECT DISTINCT
        Items_1.ImageID ,
        Items_1.SubcategoryID2 ,
        Items_1.AddDate ,
        MAX(ra0.DescPriority) AS Pri
FROM    Items AS Items_1
        INNER JOIN Attribs AS ra0 ON Items_1.ImageID = ra0.ImageID
        LEFT OUTER JOIN v_DisplayStockPrice AS v_DisplayStockPrice_1 ON Items_1.ImageID = v_DisplayStockPrice_1.ImageID
        INNER JOIN Attribs AS ra1 ON ra0.ImageID = ra1.ImageID
WHERE   ( Items_1.deleted NOT IN ( 1, 2 ) )
        AND ( Items_1.SubcategoryID2 = 'ORD' )
GROUP BY Items_1.ImageID ,
        Items_1.SubcategoryID2 ,
        Items_1.AddDate
ORDER BY Pri ,
        Items_1.AddDate DESC