查询优化

时间:2011-04-11 06:49:13

标签: mysql optimization

我需要来自不同4个类别的最新4个产品。此查询无效

SELECT 
  ProductID,ProductName,thumb
  FROM 
  tbproduct 
  WHERE 
  status =2 
GROUP BY 
`CATEGORYID` 
ORDER BY 
`ProductID` DESC 
LIMIT 4

所以我首先按所有记录订购。并使用以下查询......

SELECT 
ProductID, ProductName, thumb 
FROM 
  (
  SELECT 
  ProductID,ProductName,thumb,CATEGORYID 
  FROM 
  tbproduct 
  WHERE 
  status =2 
  ORDER BY 
  `ProductID` DESC
  ) AS tmp 
GROUP BY 
`CATEGORYID` 
ORDER BY 
`ProductID` DESC 
LIMIT 4

这个查询很慢,任何人都可以建议我快速查询。我使用MySQL。

3 个答案:

答案 0 :(得分:1)

如果您只是使用:

SELECT 
  ProductID,ProductName,thumb,CATEGORYID 
  FROM tbproduct 
  WHERE status=2
  GROUP BY CATEGORYID
  ORDER BY ProductID DESC
  LIMIT 4

答案 1 :(得分:0)

 SELECT 
  Max(ProductID), ProductName,thumb
  FROM 
  tbproduct 
  WHERE 
  status =2 
GROUP BY 
`CATEGORYID` 
ORDER BY 
 ProductID DESC 
LIMIT 4

这不起作用吗?


不确定这是否有帮助,请参阅更新后的查询。请参阅Group-by Aggragate的使用情况。

注意:这将无法可靠地返回其他列。请在此处查看left-self-exclusion join

答案 2 :(得分:0)

SELECT 
ProductID, ProductName, thumb 
FROM tbproduct 
WHERE ProductID in (
  SELECT max(ProductID)
  FROM tbproduct
  WHERE status = 2
  GROUP BY CATEGORYID
  ORDER BY ProductID DESC
  LIMIT 4
) ORDER BY ProductID DESC 

应该这样做。