I have following sql syntax. This works fine but I was wondering if there is a way to write this syntax simpler since MAX(ra0.DescPriority) uses same table join.
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
So I came up with this syntax.
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
Which SQL syntax is better? Or is there better way to write this Query?
The second one looks better and probably performs better, but really you should use Query Analyzer. It will tell you exactly which one is better:
http://msdn.microsoft.com/en-us/library/aa216945(v=sql.80).aspx
Here’s a description of how to use the query execution plan:
http://www.sql-server-performance.com/2006/query-execution-plan-analysis/