【问题标题】:How to have multiple NOT LIKE in SQL如何在 SQL 中有多个 NOT LIKE
【发布时间】:2019-03-04 15:42:26
【问题描述】:

我在一个数据库中有两个表。 ContactsFilter

Contacts 中,我有IDNameEmail 作为字段。

Filter,我有IDcode

我的目标是能够查询整个表并导出已按过滤器表中的项目过滤的列表。 (基本上与 grep -i -Ev 可以实现的相同)......基本上我想过滤掉 gmail 或 yahoo 或其他)。

如果我这样做了

select distinct email from contacts where email not like '%gmail%'

一级过滤器有效。 但如果我这样做,

select distinct email from contacts where email not like '%gmail%' or not like '%yahoo%'

然后事情开始失败。

在我开始在过滤器中集成嵌套选择代码之前,我无法让多个 where 字段不像 X 或 field1 不像 Y 工作。

非常感谢任何输入。

样本数据

name           email 
bob            bob@gmail.com
joey           joey@cisco.com

期望的输出

joey@cisco.com

更新:谢谢大家的帮助。问题第一阶段的答案是从 OR 变为 AND。 :)

第二阶段:我宁愿使用查询来确定要排除的项目(意思是如果它们中的任何一个匹配,则排除它们),而不是越来越大的查询......所以我会添加雅虎gmail protonmail 到过滤器表的代码字段中的记录.. 这样就可以了

select distinct email from contacts where email not like in (select code from filters)

这失败了,因为它说选择有多个记录

更新:

SELECT DISTINCT email FROM Contacts WHERE email NOT LIKE (select filters.code from filters where filters.id=4)

有效.. 但只提取一条记录作为过滤器。并非所有这些都是过滤器。

【问题讨论】:

  • AND 而不是OR
  • 您在 or 之后缺少字段名称,您需要为每个“不喜欢”指定一个字段 - 从电子邮件不喜欢 '%gmail%' 或电子邮件不喜欢'的联系人中选择不同的电子邮件%yahoo%'

标签: sql select where


【解决方案1】:

您只需要使用 AND 而不是 OR。

SELECT distinct email 
FROM 
    contacts 
WHERE 
    email not like '%gmail%' 
    AND email not like '%yahoo%'

【讨论】:

    【解决方案2】:

    您可以从CHARINDEX 中受益,如下所示,我认为这将提高您的查询性能。另外,您可以使用group by 代替distinct,这也有助于提高性能。

    select email 
    from contacts 
    where charindex('gmail',email) < 1 
      and charindex('yahoo',email) < 1
    group by email
    

    【讨论】:

      【解决方案3】:

      两期

      您需要每个条件的列名,因此在 OR 之后添加电子邮件

       select distinct email from contacts where email not like '%gmail%' or email not like '%yahoo%'
      

      你可能想同时检查机器人,所以你需要 AND

       select distinct email from contacts where email not like '%gmail%' AND email not like '%yahoo%'
      

      【讨论】:

        【解决方案4】:

        正如其他人所指出的,带有NOT LIKE 的正确布尔连接器是AND,而不是OR

        你可能会看到使用NOT的逻辑:

        select distinct email
        from contacts
        where not (email like '%gmail%' or email like '%yahoo%');
        

        【讨论】:

          【解决方案5】:

          如果您的选择有两个通过 OR 条件连接的 NOT LIKE 条件,那么所有内容都将满足条件。在这种情况下,“gmail”不像“yahoo”,“yahoo”也不像“gmail”,所以即使这两个也能通过标准。通过将选择转换为使用 AND 条件,您可以捕获这些情况。该语法要求您在两种情况下都提供字段名称。我觉得这段代码通俗易懂,满足你的需求。

          SELECT distinct email 
          FROM contacts 
          WHERE email not like '%gmail%' 
             AND email not like '%yahoo%'
          

          【讨论】:

          • 一个有效的点。我觉得之前的答案已经解决了上下文。我只是提供我的 Gordon 代码版本。
          • 修改评论解释我的推理
          猜你喜欢
          • 2021-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-01
          • 1970-01-01
          • 2015-07-27
          相关资源
          最近更新 更多