[英]How to optimize the SQL query with the subquery?
我想提高 SQL 查詢的性能。 我有表 'tblEntries' 和列'sTag':
+----+------+-------+------+---------+
| Id | sTag | sPath | lVer | bActive |
+====+======+=======+======+=========+
| 1 | NULL | t1 | 100 | + |
| 2 | NULL | t2 | 110 | + |
| 3 | x1 | t4 | 110 | + |
| 4 | x1 | t3 | 120 | + |
| 5 | x2 | t7 | 100 | + |
+----+------+-------+------+---------+
客戶端查詢具有指定標記的路徑,查詢應返回具有下一個條件的指定條目:
“標記”條目比“未標記”條目具有更高的優先級。
當前 SQL 查詢為:
SELECT lVer, sPath
FROM tblEntries
INNER JOIN
(SELECT MAX(lVer) AS V, sTag AS T
FROM tblEntries
WHERE bActive = TRUE
GROUP BY sTag)
ON lVer = V
WHERE T IS NULL OR T = 'user_tag'
ORDER BY T DESC
然后我可以 select 第一個滿足條件的條目。 我可以避免子查詢嗎?
謝謝!
根據您的數據和數據庫,這可能具有足夠的性能:
select top (1) e.*
from tblEntries e
where e.bActive = TRUE and
(e.t IS NULL OR e.t = 'user_tag')
order by (e.t desc), -- null values last
t.lver desc;
如果速度確實是個問題,並且您在(t, active, lver desc)
上有一個索引,那么這可能會快一點:
(select top (1) e.*
from tblEntries e
where e.t = 'user_tag' and e.bActive = TRUE
order by e.lver desc
) union all
(select top (1) e.*
from tblEntries e
where e.t is null and e.bActive = TRUE and
not exists (select 1 from tblEntries e2 where e2.t = 'user_tag' and e2.bActive = TRUE )
order by e.lver desc
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.