【问题标题】:MySQL SELECT field value(s) contained in query string查询字符串中包含的 MySQL SELECT 字段值
【发布时间】:2018-10-27 11:55:11
【问题描述】:

假设:

短语 1:我是蜘蛛侠,我有一个土豆

短语 2:我是蜘蛛,我喜欢土豆

表:

column_id | column_str
1         | spiderman
2         | potatoes

我想执行一个 SQL 查询,其中输入是短语,它应该得到结果:

对于短语 1

column_id | column_str
1         | spiderman

对于短语 2

column_id | column_str
2         | potatoes

所以,它应该在表 column_str 列的输入中找到匹配的子字符串,并返回其关联的 id。

我还没有错误或试用示例,因为我不知道从哪里开始。

我知道有 %LIKE% 匹配器。但这恰恰相反,类似于%IN_LIKE%

【问题讨论】:

  • 您使用的是 MySQL 或 MS SQL Server 还是 Sybase?

标签: mysql sql tsql


【解决方案1】:

你只需要INSTR函数:

--sample data creation
create table tbl(id int, str varchar(50));
insert into tbl values (1, 'spiderman');
insert into tbl values (2, 'potatoes');

select * from tbl
where instr('I am spiderman and I have a potato', str) > 0;

select * from tbl
where instr('I am a spider and I like potatoes', str) > 0;

参考MySQL INSTR() function

【讨论】:

    【解决方案2】:

    您应该考虑以下一些棘手的 SQL:

    select dsd
    from (select 'potato' as dsd) ss
    where (select 'I am spiderman and I have a potato') rlike dsd;
    

    例子:

    mysql> select dsd from (select 'potato' as dsd) ss where (select 'I am spiderman and I have a potato') rlike dsd;
    +--------+
    | dsd    |
    +--------+
    | potato |
    +--------+
    

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 2014-10-11
      • 2022-11-30
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 2011-05-14
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多