哪个最快?计入子查询或分组依据

时间:2014-03-03 22:47:06

标签: mysql sql optimization query-optimization

哪个最快/最有效?两者都有效。

解决方案1.按ID分组:

SELECT
    *, 
    COUNT(*) AS pages 
FROM
    notis 
WHERE
    cid = 20 
GROUP BY
    n.id
ORDER BY
    nid DESC 

解决方案2.计入子查询:

SELECT
    *,
    (select count(*) FROM notis WHERE cid=20) AS count
FROM
    notis
WHERE
    cid = 20
ORDER BY
    nid DESC

1 个答案:

答案 0 :(得分:0)

enter image description here

解决方案1是最好和最快的: 因为解决方案2有子查询

但你必须改变你的查询:

  SELECT *, COUNT(*) AS pages 
  FROM notis 
  WHERE cid = 20 
  GROUP BY nid
  ORDER BY nid DESC 

你改变了GROUP BY和ORDER BY的位置。

我不知道您是否在寻找计数(*),或者您希望每nid计算一次。如果count(*)则考虑不使用GROUP BY

 SELECT *, COUNT(*) AS pages 
 FROM notis 
 WHERE cid = 20 
 ORDER BY nid DESC