简体   繁体   中英

How to make an if statement using value from case

I have a select statement and the result is :

ax | country    | country_id | town   | pop |
1  | neverland  | 1          | ntown  | 10  |
1  | wonderland | 2          | wtown  | 20  |
2  | wonderland | 2          | wLtown | 20  |
1  | toysIsland | 3          | ttown  | 5   |

but it supposed to be like:

ax | country    | country_id | town   | pop |
1  | neverland  | 1          | ntown  | 10  |
1  | wonderland | 2          | wtown  | 20  |
2  | wonderland | 2          | wLtown | NULL|
1  | toysIsland | 3          | ttown  | 5   |

I have an if statement using value from case :

select (case country
when @c
then @co = @co +1
else @co = 1, @c = country
end ) as ax,
country, country_id, town, (case when town_id = param_ti then population_c) as pop
from tb_town a left join
tb_country b on b.country_id = a.country_id;

if ax = 1 then
 pop= pop
else
 pop= '';
end if;

I don't know what I should write in the if statement.

Try this change to your query

select (case country when @c then @co = @co +1
        else @co = 1, @c = country
        end ) as ax,
        country, country_id, town, IF(town_id = param_ti, population_c, NULL) as pop
    from tb_town a left join
         tb_country b on b.country_id = a.country_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM