为什么不考虑这个或条件

时间:2015-01-29 14:46:29

标签: sql postgresql

我有以下查询

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%';

它会返回googleyahoo或其他网址的每一行。

如果我使用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 个答案:

答案 0 :(得分:2)

我想你想要做以下事情:

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 s通常不会使用索引):

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

答案 1 :(得分:2)

您只需使用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)%'

答案 2 :(得分:0)

由于您在添加Google OR条件之后),SQL所做的是查看第一个条件,看到有匹配并返回它们,然后查看第二个条件,看看还有匹配并返回它们

使用AND,SQL必须满足两个条件才能返回...

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