【问题标题】:Search column for a string in every space separated value在每个空格分隔值中搜索字符串
【发布时间】:2015-06-04 07:40:31
【问题描述】:

假设我在数据库中有一个名为 CustomerNames 的列,其中包含值:

  1. Vins 等 al为 Chevalier 降温
  2. Magazzini Alimentari Riuniti
  3. 饥饿的猫头鹰 All-Night Grocers
  4. Split Rail Beer & Ale
  5. 阿尔freds Futterkiste

我想做一个查询,它只搜索 FIRSTNAME 和 LASTNAME 的第一个字母,并根据 FIRSTNAME 然后 LASTNAME 按 ASC 顺序列出名称。 例如,如果我在上表中搜索“al”,它应该返回如下内容:

  1. 阿尔freds Futterkiste
  2. Vins 等 al为 Chevalier 降温
  3. Split Rail Beer & Ale
  4. Magazzini Alimentari Riuniti
  5. 饥饿的猫头鹰 All-Night Grocers

我使用了下面的查询。

SELECT * FROM Customers where CustomerName LIKE 'al%' OR CustomerName LIKE '% al%' ORDER BY CustomerName 

输出:

  1. 阿尔freds Futterkiste
  2. 饥饿的猫头鹰 All-Night Grocers
  3. Magazzini Alimentari Riuniti
  4. Split Rail Beer & Ale
  5. Vins 等 al为 Chevalier 降温

仅根据名字排序结果。 但我想要一个使用名字和姓氏给出输出的查询。 谢谢。

【问题讨论】:

  • 对不起,我不明白如果名字和姓氏都在一个列中,你如何区分它们......
  • 您不需要通过给它们任何名称来区分它,可以说这些值是空格分隔的值,我想优先考虑第一个单词(在出现第一个空格之前)然后是下一个,然后是关注

标签: php mysql string search


【解决方案1】:

我认为没有直接的答案。您需要编写一个函数或存储过程来根据列值即空格分隔对结果进行排序

看看这个 MySQL: how to sort the words in a string using a stored function?

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT * FROM Customers
    where CustomerName LIKE 'al%' 
    OR CustomerName LIKE '% al%' 
    ORDER BY substring(CustomerName, instr(CustomerName, 'al'))
    

    【讨论】:

    • instr 从 MySQL 版本支持:5.6
    • 好的,所以它有效,但没有给出所需的结果。即 1.)Vins et alcools Chevalier 2.)Split Rail Beer & Ale 3.)Alfreds Futterkiste 4.)Magazzini Alimentari Riuniti 5.)Hungry Owl All-Night Grocers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多