gpt4 book ai didi

mysql - 将 IN() 子句与存储过程结合使用

转载 作者:行者123 更新时间:2023-11-29 14:51:37 26 4
gpt4 key购买 nike

我有一个存储过程,它接受一个参数,如下所示:

getData (
param varchar(500)
)
BEGIN
SELECT *
FROM category
WHERE ID in ( param );
END

给定参数为“1,2,3”,如何在没有 varchar 的“”的情况下将其设置为 1,2,3 来执行与 ID IN(1,2,2) 相同的查询 不是 ("1,2,3") 中的ID

最佳答案

恐怕非常丑陋,因为 mysql 存储过程当前不支持数组类型参数:

调用示例:

mysql> call foo('2,4,6');
+---------+----------+
| user_id | username |
+---------+----------+
| 2 | b |
| 4 | d |
| 6 | f |
+---------+----------+
3 rows in set (0.00 sec)

完整脚本:

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) unique not null
)
engine=innodb;

insert into users (username) values ('a'),('b'),('c'),('d'),('e'),('f'),('g');

drop procedure if exists foo;

delimiter #

create procedure foo
(
in p_id_csv varchar(1024)
)
proc_main:begin

declare v_id varchar(10);
declare v_done tinyint unsigned default 0;
declare v_idx int unsigned default 1;

if p_id_csv is null or length(p_id_csv) <= 0 then
leave proc_main;
end if;

-- split the string into tokens and put into an in-memory table...

create temporary table ids(id int unsigned not null)engine = memory;

while not v_done do
set v_id = trim(substring(p_id_csv, v_idx,
if(locate(',', p_id_csv, v_idx) > 0,
locate(',', p_id_csv, v_idx) - v_idx, length(p_id_csv))));

if length(v_id) > 0 then
set v_idx = v_idx + length(v_id) + 1;
insert into ids values(v_id);
else
set v_done = 1;
end if;
end while;

select u.* from users u
inner join ids on ids.id = u.user_id
order by u.username;

drop temporary table if exists ids;

end proc_main #

delimiter ;

call foo('2,4,6');

关于mysql - 将 IN() 子句与存储过程结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5619958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com