【问题标题】:Multi column search in SQLITESQLITE 中的多列搜索
【发布时间】:2017-04-27 19:47:39
【问题描述】:

我必须在 SQLITE 的多个列中搜索单个字符串,但我无法获得结果,我正在使用以下查询进行搜索:

Select * 
From MyTable 
Where (col1 || '--' || col2) like '%abc xyz 123%'

假设我在 col1 中有 'abc',在 col2 中有 'xyz 123'。 p>

任何帮助。

【问题讨论】:

  • 试试这个:Select *from yourtable where col1 like 'searchstring' or col2 like 'searchstring' etc.\
  • 您的查询会进行搜索,但在上述情况下会失败。
  • 你怎么能说它会失败。你试过了吗,它不会失败。您需要为 col 传递不同的字符串。 Select * From Yourtable where col1 like 'abc' or col2 like 'xyz 123'.
  • 我不想分开两个字符串,我可以知道哪个字符串是 col1 或 col2 的一部分,因为我必须搜索两个列的完整字符串。

标签: sqlite search


【解决方案1】:

假设我在 col1 中有“abc”,在 col2 中有“xyz 123”。

col1 || '--' || col2 等于 'abc--xyz 123',所以不会匹配 '%abc xyz 123%'

你应该使用

 SELECT * FROM MyTable WHERE col1 || ' ' || col2 LIKE '%abc xyz 123%'

 SELECT * FROM MyTable WHERE col1 || '--' || col2 LIKE '%abc--xyz 123%'

注意:不需要括号,因为|| 的优先级高于LIKE

【讨论】:

    【解决方案2】:

    LIKE 语句的操作数必须符合条件。如果您正在从这两列中的字段串联中寻找“单个字符串”完全匹配,并且 (col1) 字段具有 'abc' 而 (col2) 字段具有 'xyz 123' ...那么左侧LIKE 的操作数是串联 (col1 || col2),右侧操作数是串联 ('%abc%' || '%xyz 123%') 导致声明:

    SELECT * FROM MyTable WHERE (col1 || col2) LIKE '%abc%'||'%xyz 123%';
    

    SELECT * FROM MyTable WHERE (col1 || '--' || col2) LIKE '%abc%'||'--'||'%xyz 123%';
    

    例子:

    C:\SQLite3>sqlite3 test
        SQLite version 3.8.1 2013-10-17 12:57:35
        Enter ".help" for instructions
        Enter SQL statements terminated with a ";"
        sqlite> CREATE table MyTable (col1 text, col2 text);
        sqlite> INSERT into MyTable (col1, col2) values ('abc', 'xyz 123');
        sqlite> SELECT * FROM MyTable WHERE (col1 || col2) LIKE '%abc xyz 123%';
        sqlite> SELECT * FROM MyTable WHERE (col1 || col2) LIKE '%abc%' || 'xyz 123%';
        abc|xyz 123
        sqlite> SELECT * FROM MyTable WHERE (col1 ||'--'|| col2) LIKE '%abc xyz 123%';
        sqlite> SELECT * FROM MyTable WHERE (col1 ||'--'|| col2) LIKE '%abc%'||'--'||'%xyz 123%';
        abc|xyz 123
        sqlite>
    

    【讨论】:

      【解决方案3】:

      正确的答案是我必须像这样修改上面的查询,

      Select * From MyTable Where (col1 || ' ' || col2) like '%abc xyz 123%'
      

      【讨论】:

        猜你喜欢
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2011-01-01
        • 1970-01-01
        • 2015-05-25
        相关资源
        最近更新 更多