代码之家  ›  专栏  ›  技术社区  ›  Andy K Haimei

为什么不考虑或条件

  •  0
  • Andy K Haimei  · 技术社区  · 11 年前

    我有以下问题

    SELECT url
    FROM 
    table_repo3
    WHERE
    (url LIKE '%auto%'
    OR url LIKE '%automobile%' 
    OR url LIKE '%voiture%'
    OR url LIKE '%bagnole%'
    OR url LIKE '%vehicule%'
    OR url LIKE '%berline%'
    OR zpages LIKE '%auto%'
    OR zpages LIKE '%automobile%' 
    OR zpages LIKE '%voiture%'
    OR zpages LIKE '%bagnole%'
    OR zpages LIKE '%vehicule%'
    OR zpages LIKE '%berline%')
    OR url like '%google%';
    

    它返回我,每一行 google 和 yahoo 或其他URL。

    如果我使用 AND 而不是最后一个 OR ,我有 无结果 .

    为了能够应用谷歌的条件,我做了以下操作

    CREATE TEMPORARY TABLE toto 
    SELECT *
    FROM 
    table_repo3
    WHERE
    (url LIKE '%auto%'
    OR url LIKE '%automobile%' 
    OR url LIKE '%voiture%'
    OR url LIKE '%bagnole%'
    OR url LIKE '%vehicule%'
    OR url LIKE '%berline%'
    OR zpages LIKE '%auto%'
    OR zpages LIKE '%automobile%' 
    OR zpages LIKE '%voiture%'
    OR zpages LIKE '%bagnole%'
    OR zpages LIKE '%vehicule%'
    OR zpages LIKE '%berline%')
    ;
    

    然后

    SELECT url FROM temporary_table WHERE url LIKE '%google%';
    

    此解决方案有效,但冗长乏味。

    有什么更容易的吗?

    TIA一如既往。

    3 回复  |  直到 11 年前
        1
  •  2
  •   David Faber    11 年前

    我认为您需要执行以下操作:

    SELECT *
      FROM table_repo3
     WHERE url LIKE '%google%'
       AND ( url LIKE '%auto%'
          OR url LIKE '%automobile%' 
          OR url LIKE '%voiture%'
          OR url LIKE '%bagnole%'
          OR url LIKE '%vehicule%'
          OR url LIKE '%berline%'
          OR zpages LIKE '%auto%'
          OR zpages LIKE '%automobile%' 
          OR zpages LIKE '%voiture%'
          OR zpages LIKE '%bagnole%'
          OR zpages LIKE '%vehicule%'
          OR zpages LIKE '%berline%' );
    

    但这真的不是一个好办法。您可以改用正则表达式,但即使这样也可能无法加快速度( LIKE 带前导通配符的通常不会使用索引):

    SELECT * FROM table_repo3
     WHERE url LIKE '%google%'
       AND ( url ~ '(auto)?mobile|voiture|bagnole|vehicule|berline'
          OR zpages ~ '(auto)?mobile|voiture|bagnole|vehicule|berline' );
    
        2
  •  2
  •   A l w a y s S u n n y    11 年前

    您只需使用 SIMILAR TO 在里面 Postgres 对于多个 Like 检查,试试这个方法。

    SELECT url
      FROM 
    table_repo3
      WHERE
    url SIMILAR TO '%(auto|automobile|voiture|bagnole|vehicule|berline|google)%'
      OR 
    zpages SIMILAR TO'%(auto|automobile|voiture|bagnole|vehicule|berline)%'
    
        3
  •  0
  •   JustAPup    11 年前

    由于在)之后添加了Google OR条件,所以SQL所做的是查看第一个条件,查看是否存在匹配项并返回它们,然后查看第二个条件,看看是否也存在匹配项,并返回它们。

    使用AND时,必须满足这两个条件,SQL才能返回某个值。。

    如果还不清楚,你应该对OR和and条件进行一些研究。。