MySQL IF結果計數0返回消息

[英]MySQL IF Result Count 0 Return Message


I need the following query to return a message, such as "No Result" if the Record Count = 0.

如果記錄計數= 0,我需要以下查詢來返回消息,例如“無結果”。

set @ID_CARTERA = 1;

select    

LEFT(A.F_ANOTRIMESTRE, 4 ) Year,
RIGHT(A.F_ANOTRIMESTRE, 2 ) Quarter,
ROUND ( A.POR_RENTABILIDAD, 2 ) Quarterly_Yield

from      dr_rent_carteras_trimestres A

where     A.ID_CARTERA = @ID_CARTERA
And       (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select    MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
                                         from      dr_rent_carteras_trimestres
                                         where     ID_CARTERA = @ID_CARTERA ) 
            and
            RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) 

1 个解决方案

#1


0  

you can trick the system like this:

你可以像這樣欺騙系統:

  1. generate a query to return COUNT(*). This will always return a row, even if there are zero rows to count

    生成一個返回COUNT(*)的查詢。這將始終返回一行,即使要計數零行也是如此

  2. Left join your main query with the COUNT(*) query. Use Case statement to replace the results with "No Results".

    左連接您的主查詢與COUNT(*)查詢。使用Case語句將結果替換為“No Results”。

So, the resulting query will look like (assumption - the main query returns zero or one record only - thus there is no ON clause in the LEFT JOIN!!!!):

因此,結果查詢看起來像(假設 - 主查詢僅返回零或一個記錄 - 因此LEFT JOIN中沒有ON子句!!!!):

set @ID_CARTERA = 1;

select    
CASE cnt WHEN 0 THEN "No Results" ELSE Year END,
Quarter,
Quarterly_Yield
FROM
(select count(*) AS cnt
from      dr_rent_carteras_trimestres A
where     A.ID_CARTERA = @ID_CARTERA
And       (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select    MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
                                         from      dr_rent_carteras_trimestres
                                         where     ID_CARTERA = @ID_CARTERA ) 
            and
            RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) ) cnt_tbl
LEFT JOIN
( select    
LEFT(A.F_ANOTRIMESTRE, 4 ) Year,
RIGHT(A.F_ANOTRIMESTRE, 2 ) Quarter,
ROUND ( A.POR_RENTABILIDAD, 2 ) Quarterly_Yield
from      dr_rent_carteras_trimestres A
where     A.ID_CARTERA = @ID_CARTERA
And       (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select    MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
                                         from      dr_rent_carteras_trimestres
                                         where     ID_CARTERA = @ID_CARTERA ) 
            and
            RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) ) main_tbl

The same thing can be accomplished with UNION. Ask in the comments if you wish me to show how

UNION可以完成同樣的事情。請在評論中詢問您是否希望我展示如何


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/01/31/8c0c1ac3c654814e678dcc6de3f98a2.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com