最近,有人要求我编写查询以从包含此类实体最大数量的组中选择实体的属性。因此,我以几种方式在Northwind(MSFT该操作在数据库上进行。$ a; d# q4 q8 d: y" V' n; D N
一:: I3 w" z+ w& f. {6 X9 f
SELECT cat.CategoryName,prod.ProductName FROM Categories cat JOIN Products prod ON cat.CategoryID = prod.CategoryID JOIN (SELECT TOP 1 p.CategoryID,COUNT(p.ProductId) as products FROM Categories c JOIN Products p on c.CategoryID = p.CategoryID GROUP BY p.CategoryID ORDER BY products desc) c ON c.CategoryID = cat.CategoryID二: " p8 z$ Y. r! ^* K4 ZSELECT cat.CategoryName,prod.ProductName FROM Categories cat JOIN Products prod ON cat.CategoryID = prod.CategoryID JOIN (SELECT CategoryID,COUNT(ProductID) m_count FROM Products GROUP BY CategoryID HAVING COUNT(ProductID) = (SELECT MAX(sub.cnt) FROM (SELECT CategoryId,COUNT(ProductID) cnt FROM Products GROUP BY CategoryId) sub)) m ON m.CategoryID = cat.CategoryID问题是: 为什么更快 ?在执行计划中,没有什么特别突出的。时间稍有不同,但大致相同。数据库当然很小。/ @, H5 h, `* N2 w F9 l2 Z* S6 X
2 S. E3 e: k A 解决方案: