MySQL IF结果计数0返回消息

时间:2013-01-31 22:36:11

标签: mysql sql select

如果记录计数= 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 个答案:

答案 0 :(得分:0)

你可以像这样欺骗系统:

  1. 生成一个返回COUNT(*)的查询。这将始终返回一行,即使有零行计数

  2. 使用COUNT(*)查询左连接主查询。使用Case语句将结果替换为“No Results”。

  3. 因此,结果查询看起来像(假设 - 主查询只返回零或一条记录 - 因此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
    

    使用UNION可以完成同样的事情。如果您希望我展示如何

    ,请在评论中提问