首页 文章

MySQL使用IN编写语句

提问于
浏览
2

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

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

set @a='tag1, tag2' ;

execute stmt1 using @a ;

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

是否可以在准备好的声明中使用 in 形成这样的列表?

2 回答

  • 3

    简而言之,没有 .

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

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

  • 1

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

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

    prepare stmt1 from 'select * from tags where name in (?, ?)'
    
    set @a='tag1';
    set @b='tag2';
    
    execute stmt1 using @a, @b;
    

相关问题