简体   繁体   English

如何在MySQL存储过程中使用WHERE IN

[英]how to use WHERE IN mysql stored procedure

How do I pass an array and use WHERE IN inside stored procedure? 如何传递数组并在存储过程中使用WHERE IN?

Do i need to concatenate input string or something ? 我是否需要连接输入字符串或其他内容?

Lets say 可以说

DELIMITER $$
DROP PROCEDURE IF EXISTS `abc`.`table1`$$
CREATE PROCEDURE  `abc`.`test`
(IN somestring VARCHAR(255))
BEGIN
    SELECT * FROM abc.table1 
    WHERE flight_type IN somestring
END $$
DELIMITER ;

You can use the string concatenation and the PREPARE statement to run dynamically built queries. 您可以使用字符串连接和PREPARE语句来运行动态构建的查询。

somestring must be constructed in a valid SQL format like '1','2','3' 必须以有效的SQL格式(例如'1','2','3'构造somestring

DELIMITER $$
DROP PROCEDURE IF EXISTS `abc`.`table1`$$
CREATE PROCEDURE  `abc`.`test`
(IN somestring VARCHAR(255))
BEGIN
    @s=CONCAT("
    SELECT * FROM abc.table1 
    WHERE flight_type IN (",somestring,");")
    PREPARE stmt FROM @s;
    EXECUTE @s;
END $$
DELIMITER ;

You can use FIND_IN_SET() if somestring is formatted a,b,c,d : 如果somestring的格式为a,b,c,d则可以使用FIND_IN_SET()

SELECT *
FROM abc.table1
WHERE FIND_IN_SET(flight_type, somestring)

This should work as long as somestring is of the form 只要somestring为以下形式,就可以使用

"(item1, item2, item3, ... )"

if not, you could format it accordingly inside of your SP but I'm not sure what the best practice is. 如果没有,您可以在SP中相应地对其进行格式化,但是我不确定最佳做法是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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