[英]Stored Procedure with a IN statement (mysql)
我有一个查询
Select id,name,... FROM table WHERE id IN (?)
使用联接和另一个具有相同ID的(?),查询实际上更加复杂。 我被告知将其放在存储过程中,以使其更易于管理和安全,但是mysql不支持数组,因此我不确定这样做是最好的方法,因此我不确定知道我必须通过多少个ID。 我见过有人通过弦。 这是唯一的方法吗?
您可以使用临时表。 尽管此答案的投票不高,所以我认为使用字符串参数是首选方法(17票对2票)(请参阅链接)。 临时表的答案来自另一个问题:将数组传递给MySQL存储例程
对临时表使用联接。 您不需要将临时表传递给函数,它们是全局的。
create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;
delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
-- use the temporary table `ids` in the SELECT statement or
-- whatever query you have
select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;
CALL tsel() ; -- call the procedure
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.