MySQL使用IN编写语句

时间:2010-12-22 01:14:09

标签: mysql prepared-statement

我想执行一个准备好的语句,如


prepare stmt1 from 'select * from tags where name in (?)'

set @a='tag1, tag2' ;

execute stmt1 using @a ;

但是,它没有按预期工作(似乎将in的参数视为单个字符串)。

是否可以在预准备语句中使用in形成这样的列表?

2 个答案:

答案 0 :(得分:3)

简而言之,没有。

您告诉尝试运行的基本查询是select * from foo where bar in ('tag1, tag2'),这意味着它与字符串 'tag1, tag2'匹配,而不是将其视为列表。< / p>

不幸的是,对于in,您通常需要进行动态查询。其他选项是解析字符串的UDF,或者您加入的临时表。

答案 1 :(得分:1)

没有。您可以动态构建SQL(例如使用CONCAT),然后执行它。

或者您可以使用多个参数:

prepare stmt1 from 'select * from tags where name in (?, ?)'

set @a='tag1';
set @b='tag2';

execute stmt1 using @a, @b;