本文介紹了將 SELECT COUNT 優(yōu)化為 EXISTS的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我有一個(gè)查詢要從表中查找某些客戶.
I have a query to find certain customers from a table.
SELECT COUNT(*)
FROM CUSTOMER
WHERE amount <> 0
AND customerid = 22
customerid 上有一個(gè)索引,所以數(shù)據(jù)庫(kù)會(huì)掃描 customerid = 22 的所有行.
There is an index on customerid, so the DB scans all rows with customerid = 22.
由于結(jié)果是通過(guò)檢查計(jì)數(shù)返回零還是大于零來(lái)處理的,我該如何優(yōu)化查詢?IE.這樣,在金額 <> 0 的第一個(gè)客戶行,查詢返回 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
這篇關(guān)于將 SELECT COUNT 優(yōu)化為 EXISTS的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!