SQL计数查询的性能改进

时间:2013-05-21 09:31:17

标签: mysql sql join

我将使用什么类型的SQL查询来转换以下内容;

|  ID  |  SERIAL  |  LCN  | INITLCN |
|------|----------|-------|---------|
|  1   |    A     |  A1   |         |
|  2   |    B     |  A2   |         |
|  3   |    C     |  A3   |   A1    |
|  4   |    D     |  A4   |   A2    |
|  5   |    E     |  A5   |   A1    |
|------|----------|-------|---------|

进入类似于此的结果;

|  ID  |  COUNT  |
|------|---------|
|  1   |    2    |
|  2   |    1    |
|------|---------|

使用我的低SQL技能,我设法写下面的查询,但它非常慢;

select
  a.id,
  count (b.id) as parent
from assets a 
left join assets b
  ON (a.lcn = b.initlcn)
group by a.id
order by a.id;

3 个答案:

答案 0 :(得分:0)

select
t1.ID,
t1.LCN,
COUNT(*)
from
Table1 t1
INNER JOIN Table1 t2 ON t1.LCN = t2.INITLCN
GROUP BY t1.LCN

看到它在sqlfiddle中正常工作。

答案 1 :(得分:0)

也许两个表连接不是nesecerry。 试试这个

select 
a.id
,b.cnt
from assets a
join (
 select 
 initlcn
 count(1) cnt
 from assets
 group by initlcn
)
b on (a.lcn=b.initlcn)

答案 2 :(得分:0)

您也可以测试以下查询 -

我已经检查了您发布的查询和以下查询的执行计划,我两者之间的差异很大 -

SELECT t_1.Id, t_2.Cnt
  FROM Assets t_1,
       (SELECT Initlcn, COUNT(*) Cnt FROM Assets GROUP BY Initlcn) t_2
 WHERE t_1.Lcn = t_2.Initlcn