为什么无法对 mysql 过程中的 if 语句进行正确的逻辑查询?

Why can't get right logical query for the if statement in mysql procedure?

查询所有年份为18的数据:

SELECT * from tb where year=18 //
+----+------+------+------+
| id | name | year | num  |
+----+------+------+------+
|  2 | a    |   18 |  400 |
|  4 | b    |   18 |  200 |
|  6 | c    |   18 |  100 |
+----+------+------+------+

现在我写了一个mysql程序:

create procedure show_data(in type char,myear int)
begin
if type = "all" then 
    SELECT * from tb where year=myear;
elseif type != "all" then
    SELECT * from tb where name=type and year=myear;
end if;
end //

过程show_data中的逻辑是clear:when输入参数type是all,myear是18,查询就是SELECT * from tb where year=18到程序。

我用call show_data("all",18)得到的结果如下:

call show_data("all",18)//
+----+------+------+------+
| id | name | year | num  |
+----+------+------+------+
|  2 | a    |   18 |  400 |
+----+------+------+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected, 1 warning (0.00 sec)

show warnings//
+---------+------+-------------------------------------------+
| Level   | Code | Message                                   |
+---------+------+-------------------------------------------+
| Warning | 1265 | Data truncated for column 'type' at row 1 |
+---------+------+-------------------------------------------+
1 row in set (0.00 sec)

您正在将变量 type 声明为 char。这只允许一个字符。因此,当您尝试分配包含三个字符 ('all') 的字符串时出现错误。

考虑 this example:

delimiter //
create procedure debug_char(in type char, myear int)
begin
    select type;
end 
//

call debug_char('abc', 1);

产量:

Error: ER_DATA_TOO_LONG: Data too long for column 'type' at row 1

您需要将数据类型更改为 char(3) 以便该值适合它(如果超过 3,您实际上需要与列 name 中相同的最大字符长度)。

注意:可以通过将逻辑移至查询本身而不是使用 if 来简化您的代码,如下所示:

delimiter //
create procedure debug_char(in type char(3), myear int)
begin
    select * from tb where (name = type or type = 'all') and year = myear;
end
//