【问题标题】:Query for exact match of a string in SQL在 SQL 中查询字符串的精确匹配
【发布时间】:2011-06-28 05:48:30
【问题描述】:

我想从数据库表中查询字符串的完全匹配。

当我把查询写成

select description from tproduct where description like '%diamond%'

它运行并以wild card 查询的形式给出结果。比如我有ringdiamond、diamondmaster等。

但我只想得到“钻石”。

为此,我这样做了:

select description from tproduct where description = 'diamond'

但它给出了一个错误:

错误:“where 子句”中的未知列“钻石”

描述栏包含:

This bracelet is composed of round diamond surrounded by milgrain detailing. Its secure setting prevents it from twisting and ensures it will sit impeccably on her wrist.


This stylish design is the perfect accessory for the day or evening. Akoya cultured pearls are lined up by a string of bezel-set round diamond.

【问题讨论】:

  • 你确定不是不小心使用了双引号吗?
  • @John Gibb:是的,我很确定。我只用了单引号
  • 如果你想使用LIKE,只需使用不带通配符的select description from tproduct where description like 'diamond'
  • @Balanivash:我也试过了,但没用 :(
  • @Romi:我确信上面的查询与您可能正在运行的查询不同。上面的查询没有任何问题。但正如您的错误消息所说,它将“钻石”作为一列读取,如果您在“钻石”周围使用反引号(`)而不是单引号(')

标签: mysql sql


【解决方案1】:

如果我正确理解了这个问题,您想匹配“diamond”,因为它是一个独特的词,而不是另一个词(如“diamondville”)的一部分。您可以执行 SELECT * FROM tproduct WHERE description like '% diamond %' 之类的操作,这将匹配所有“diamond”被空格包围的记录。

但这行不通。这不会找到描述以“Diamond”开头或在“Diamond”之后有逗号或句点的记录

您需要匹配正则表达式。您可以使用它指定单词边界:

select * from t2 where description regexp '[[:<:]]diamond[[:>:]]';

有关 MySQL 正则表达式的更多信息,请参阅此页面:http://dev.mysql.com/doc/refman/5.1/en/regexp.html

【讨论】:

    【解决方案2】:

    您可以使用带有特殊模式的正则表达式作为单词边界。

    select description from tproduct 
    where description regexp '[[:<:]]diamond[[:>:]]'
    

    REGEXP

    【讨论】:

      【解决方案3】:
      select description from tproduct where description like 'diamond'
      

      【讨论】:

      • @Romi,你能给我表格结构吗
      【解决方案4】:

      对于 SQL Server: Description
      SELECT description FROM tproduct WHERE description ='diamond' COLLATE SQL_Latin1_General_CP1_CS_AS

      【讨论】:

      • 为什么附加COLLATE SQL_Latin1_General_CP1_CS_AS 有帮助?不就是排序顺序吗?
      • 更笼统地说,您能否解释一下它的作用和工作原理(通过编辑您的答案,而不是在 cmets 中回答)?
      【解决方案5】:
      select description from tproduct where description = 'diamond'
      

      【讨论】:

        猜你喜欢
        • 2016-03-07
        • 2019-04-14
        • 2021-10-18
        • 1970-01-01
        • 2022-11-26
        相关资源
        最近更新 更多