我有以下查询,如果表数据增长并包含数百万条记录,是否会导致性能问题?可以通过我在选择几次中选择count()的方式来增强它吗?我已经在6列上添加了索引。 我知道连接不好我已经在增强查询
SELECT
P.CID,
P.CB,
(SELECT COUNT(1)
FROM EED_TABLE F
WHERE F.ID = P.ID
AND F.BC = P.BC
AND F.PCD = P.PCD
AND F.CID = P.CID
AND F.BRC = P.BRC
AND F.ST = 'F') ST_F,
(SELECT COUNT(1)
FROM EED_TABLE N
WHERE N.ID = P.ID
AND N.BC = P.BC
AND N.PCD = P.PCD
AND N.COMP_CODE = P.COMP_CODE
AND N.BRC = P.BRC
AND N.ST = 'N') ST_N,
(SELECT COUNT(1)
FROM EED_TABLE A
WHERE A.ID = P.ID
AND A.BC = P.BC
AND A.PCD = P.PCD
AND A.CID = P.CID
AND F.BRC = P.BRC
AND A.ST = 'A') ST_A
FROM EED_TABLE P ,EDD_DEF D
WHERE P.PCD = D.PCD
AND P.BC= D.BC
AND P.CD= 1
AND P.ID = 1
AND P.BC= 22
AND P.PCD = 31
答案 0 :(得分:1)
我总是更愿意选择JOIN
而不是选择更多的陈述,这就是我要做的事情,当然不知道你的数据所以也许它不会工作,但是给它一个机会让我知道结果和速度
select
p.cid, p.cb, SUM(case when f.id is not null then 1 else 0 end) st_f,
, SUM(case when a.id is not null then 1 else 0 end) st_a
, SUM(case when n.id is not null then 1 else 0 end) st_n
from eed_table p
join edd_def d on p.pcd = d.pcd and p.bc = d.bc
left join eed_table f on f.id = p.id and f.bc = p.bc
and f.pcd = p.pcd and f.cid = p.cid
and f.brc = p.brc and f.st = 'f'
left join eed_table a on p.id = a.id and p.bc = a.bc
and p.pcd = a.pcd and p.cid = a.cid
and p.brc = a.brc and a.st = 'a'
left join eed_table n on n.id = p.id and n.bc = p.bc
and n.pcd = p.pcd and n.comp_code = p.comp_code
and n.brc = p.brc and n.st = 'n'
where p.cd = 1 and p.id = 1 and p.bc = 22 and p.pcd = 31
group by p.cid, p.cb
答案 1 :(得分:1)
似乎您的查询可以使用窗口函数重写:
SELECT
DISTINCT P.CID, P.CB
, SUM(CASE WHEN P.ST = 'F' THEN 1 ELSE 0 END) OVER (PARTITION BY P.ID, P.BC, P.PCD, P.CID, P.BRC) ST_F
, SUM(CASE WHEN P.ST = 'N' THEN 1 ELSE 0 END) OVER (PARTITION BY P.ID, P.BC, P.PCD, P.COMP_CODE, P.BRC) ST_N
, SUM(CASE WHEN P.ST = 'A' THEN 1 ELSE 0 END) OVER (PARTITION BY P.ID, P.BC, P.PCD, P.CID, P.BRC) ST_A
FROM
EED_TABLE P
WHERE
P.CD = 1
AND P.ID = 1
AND P.BC = 22
AND P.PCD = 31
AND EXISTS (SELECT 1 FROM EDD_DEF D WHERE P.PCD = D.PCD AND P.BC= D.BC)