如何使用case中的值创建if语句

时间:2015-07-30 13:29:40

标签: mysql sql if-statement case

我有一个select语句,结果是:

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   |

但它应该是这样的:

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   |

我使用if的值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;

我不知道我应该在if声明中写些什么。

1 个答案:

答案 0 :(得分:1)

尝试对您的查询进行此更改

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;