我有以下查询:
SELECT (CASE WHEN cc.id IS NULL THEN dc.id ELSE cc.id END) AS id,
l.CALL,l.QSO_DATE,cc.prefix,l.state,l.QSL_RCVD,l.Band,l.Mode,
(CASE WHEN CC.Country IS NULL THEN dc.Country ELSE cc.Country END) AS country,
(CASE WHEN CC.Country IS NULL THEN 'Y' ELSE 'N' END) AS 'deleted',
(CASE WHEN CC.flags IS NULL THEN dc.flags ELSE cc.flags END) AS 'flag'
FROM lotw l
LEFT OUTER JOIN CountryCode AS cc on cc.code = l.dxcc
LEFT OUTER JOIN DeleteCountry AS dc on dc.code = l.dxcc
WHERE l.DXCC > ''
GROUP BY CC.Country,dc.Country ORDER BY cc.COUNTRY,dc.COUNTRY.
返回一组与国家/地区代码表代码字段匹配的唯一国家/地区。 速度不到一秒钟。
我需要扩展它,以便查询选择LOTW表中最早的QSLRDATE。 所以我修改了这样的查询:
SELECT (CASE WHEN cc.id IS NULL THEN dc.id ELSE cc.id END) AS id, l.CALL,l.QSO_DATE,cc.prefix,l.state,l.QSL_RCVD,l.Band,l.Mode,
(CASE WHEN CC.Country IS NULL THEN dc.Country ELSE cc.Country END) AS country,
(CASE WHEN CC.Country IS NULL THEN 'Y' ELSE 'N' END) AS 'deleted',
(CASE WHEN CC.flags IS NULL THEN dc.flags ELSE cc.flags END) AS 'flag'
FROM lotw l
LEFT OUTER JOIN CountryCode AS cc on cc.code = l.dxcc
LEFT OUTER JOIN DeleteCountry AS dc on dc.code = l.dxcc
WHERE l.QSLRDATE = (SELECT MIN(l2.QSLRDATE) FROM LOTW l2 WHERE l2.DXCC=l.DXCC) AND l.DXCC > ''
GROUP BY CC.Country,dc.Country ORDER BY cc.COUNTRY,dc.COUNTRY
这可行,但性能从不到一秒钟到15秒。 我添加的子查询:
l.QSLRDATE = (SELECT MIN(l2.QSLRDATE) FROM LOTW l2 WHERE l2.DXCC=l.DXCC)
不是实现我想要的最佳方式。 任何帮助都会很棒。
答案 0 :(得分:0)
尝试加入子查询,而不是在WHERE子句中使用相关的子查询。
SELECT
(CASE WHEN cc.id IS NULL THEN dc.id ELSE cc.id END) AS id,
l.CALL,l.QSO_DATE,cc.prefix,l.state,l.QSL_RCVD,l.Band,l.Mode,
(CASE WHEN CC.Country IS NULL THEN dc.Country ELSE cc.Country END) AS country,
(CASE WHEN CC.Country IS NULL THEN 'Y' ELSE 'N' END) AS 'deleted',
(CASE WHEN CC.flags IS NULL THEN dc.flags ELSE cc.flags END) AS 'flag'
FROM
(SELECT dxcc, MIN(qslrdate) AS qslrdate FROM lotw GROUP BY dxcc) AS qslr
INNER JOIN lotw AS l ON l.dxcc = qslr.dxcc AND l.qslrdate = qslr.qslrdate
LEFT OUTER JOIN CountryCode AS cc on cc.code = l.dxcc
LEFT OUTER JOIN DeleteCountry AS dc on dc.code = l.dxcc
WHERE l.DXCC > ''
GROUP BY CC.Country,dc.Country ORDER BY cc.COUNTRY,dc.COUNTRY
另外,请确保lotw
在(dxcc, qslrdate)
上有索引,以确保子查询和联接都能正常运行。
事实上,确保首先拥有该索引,然后重试您的查询。然后,如果性能仍然很差,请尝试以上查询。