【问题标题】:SQL select query with wildcard on input parameter在输入参数上使用通配符的 SQL 选择查询
【发布时间】:2011-07-24 17:40:01
【问题描述】:

基本上和我的other thread 相同的问题!

我有一个 db 表,我需要编写一个查询,该查询将根据字符串的部分匹配返回结果。

Example: 

DB field: abc 

Search term: 123abc

i.e. I want given 123abc for it to return the row that has the abc field in it!

My attempt:

SELECT mood from users where '$searchTerm' like '%' || dbField

这样的事情有可能吗?


嗯,基本上我正在尝试将数字与搜索词 la77740985 匹配

id   | mood  | numberfield
====   =====   ============
1      bad      '77740985'
2      good     '77513755'

运行查询会返回两行!

注意:通配符只能在字符串的开头,换句话说,我希望搜索词以任何开头,但仍匹配数据库中基本上具有相同结尾的字符串。

【问题讨论】:

    标签: sql sqlite select wildcard sql-like


    【解决方案1】:

    它是这样工作的:

    从 '$searchTerm' like concat('%',numberField); 的用户中选择心情

    【讨论】:

      【解决方案2】:
      SELECT mood
      from users
      where '$searchTerm' like '%' || numberField
      

      这将匹配 $searchTerm = '123abc' 与包含 'abc' 的 dbField。这是正确的。如果您需要包含(任何地方),请在末尾添加|| '%'

      完整的测试脚本

      drop table if exists users2;
      create table users2 (mood, numberfield);
      insert into users2(mood,numberfield) values ('happy','77740985');
      insert into users2(mood,numberfield) values ('sad','77513755');
      

      然后运行这个

      SELECT mood from users2 where 'la77740985' like ('%' || numberfield);
      

      输出

      mood
      =======
      'happy'
      

      【讨论】:

      • @Richard 是的,但由于某种原因它也匹配其他不相关的字段!
      • @mixkat - 你能列出一些例子吗(编辑问题) - 也可以看看我编辑的答案
      • @Richard 它不在我的身上!它返回两个字段!
      • @mixkat 请使用both fields 和 $searchTerm 的值编辑问题,以便我们可以在同一页面上工作
      • @Richard 编辑了问题!
      猜你喜欢
      • 1970-01-01
      • 2013-11-12
      • 2022-07-07
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多