杜松子酒没有在JOIN中同时在两列上使用

时间:2016-07-15 06:27:10

标签: postgresql postgresql-9.4

我有两个表,productsproducts_names

我在两个表中使用GIN索引在两列中进行ILIKE匹配,但仅当我在一列上执行ILIKE时才使用GIN。

我通过UNION 做了一个解决方法,但我想知道它为什么不能正常工作。

列{C}}和n.name都是VARCHAR,它们上面都有GIN索引:

e.producer
  

选择JOIN和ILIKE 不使用GIN

CREATE INDEX products_producer_gin_idx ON products USING gin (producer gin_trgm_ops);
CREATE INDEX products_names_name_gin_idx ON products_names USING gin (name gin_trgm_ops);
  

在单个列n.name上选择使用GIN

testdb=# explain (analyze, verbose) 
            SELECT n.name, e.producer
            FROM products e
            INNER JOIN products_names n ON 
                n.product_id = e.product_id

            WHERE

                    n.name ilike '%eda%' or e.producer ilike '%eda%' 


limit 20;
                                                                                 QUERY PLAN                                                                                 
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.42..2725.92 rows=20 width=60) (actual time=0.582..62.658 rows=20 loops=1)
   Output: n.name, e.producer
   ->  Nested Loop  (cost=0.42..669928.73 rows=4916 width=60) (actual time=0.582..62.652 rows=20 loops=1)
         Output: n.name, e.producer
         ->  Seq Scan on public.products e  (cost=0.00..220800.16 rows=446716 width=29) (actual time=0.002..5.363 rows=17067 loops=1)
               Output: e.producer, e.product_id
         ->  Index Scan using products_names_pkey on public.products_names n  (cost=0.42..1.00 rows=1 width=39) (actual time=0.003..0.003 rows=0 loops=17067)
               Output: n.product_id, n.lang, n.name, n.name2, n.name3, n.products
               Index Cond: (n.product_id = e.product_id)
               Filter: (((n.name)::text ~~* '%eda%'::text) OR ((e.producer)::text ~~* '%eda%'::text))
               Rows Removed by Filter: 1
 Planning time: 0.559 ms
 Execution time: 62.677 ms
(13 Zeilen)

Zeit: 63,529 ms

1 个答案:

答案 0 :(得分:0)

这些只是一种解决方法。你可以推动postgres做索引。

SELECT * from
    (SELECT n.name, e.producer
        FROM products e
        INNER JOIN products_names n ON 
            n.product_id = e.product_id) a    
    WHERE
            name ilike '%eda%' or producer ilike '%eda%' 
  

编辑 - 或试试这个

SELECT * FROM
    (SELECT n.name, e.producer
        FROM products e
        INNER JOIN products_names n ON 
            n.product_id = e.product_id
        WHERE
                n.name ilike '%eda%'  )a
    WHERE a.producer ilike '%eda%'