本文介紹了將 SELECT COUNT 優化為 EXISTS的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個查詢要從表中查找某些客戶.
I have a query to find certain customers from a table.
SELECT COUNT(*)
FROM CUSTOMER
WHERE amount <> 0
AND customerid = 22
customerid 上有一個索引,所以數據庫會掃描 customerid = 22 的所有行.
There is an index on customerid, so the DB scans all rows with customerid = 22.
由于結果是通過檢查計數返回零還是大于零來處理的,我該如何優化查詢?IE.這樣,在金額 <> 0 的第一個客戶行,查詢返回 0,否則如果所有行都 = 0,則返回 1.
Since the result is processed by checking whether the count returns zero or more than zero, how can I optimize the query? I.e. such that at the first customer row with amount <> 0 the query returns 0 else if all rows are = 0, then return 1.
推薦答案
select case
when exists (select *
from customer
where amount <> 0
and customerid = 22) then 1
else 0
end as non_zero_exists
這篇關于將 SELECT COUNT 優化為 EXISTS的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!