1

我将使用什么类型的 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;
4

3 回答 3

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
于 2013-05-21T10:04:39.750 回答
0
select
t1.ID,
t1.LCN,
COUNT(*)
from
Table1 t1
INNER JOIN Table1 t2 ON t1.LCN = t2.INITLCN
GROUP BY t1.LCN

看到它在sqlfiddle中工作。

于 2013-05-21T09:38:37.447 回答
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)
于 2013-05-21T09:41:59.660 回答