簡體   English   中英

如何使用子查詢優化 SQL 查詢?

[英]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  |   +     |
+----+------+-------+------+---------+

客戶端查詢具有指定標記的路徑,查詢應返回具有下一個條件的指定條目:

  1. 如果有一個帶有指定標簽的條目,它應該返回具有最大 lVer 值的條目,並且 bActive 應該是 TRUE。
  2. 如果沒有帶有指定標簽的條目,它應該返回帶有 NULL sTag 值和最大 lVer 值的條目,並且 bActive 應該為 TRUE。

“標記”條目比“未標記”條目具有更高的優先級。

當前 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM