2017-08-02 62 views
0

不是SQL专家,但我设法使这个查询工作,并提供我需要的结果。诀窍是获得它的表现。这两张桌子都会有大约6百万条记录。它目前运行时间约3分钟,这是我需要的方式。Postgres多个联接

SELECT p.id, 
     match.weight 
FROM store_promotions p 
LEFT JOIN 
    (SELECT * 
    FROM 
    (SELECT id, 
      (facets.weight::int * 1.5) AS weight 
     FROM store_promotions promos 
     JOIN -- this will return all promos, but add weight of 1.5 to the ones that are better matched to customer 

     (SELECT (jsonb_array_elements(product) ->> 'key') AS barcode, 
       (jsonb_array_elements(product) ->> 'doc_count') AS weight 
     FROM customer_transaction_facets 
     WHERE account_id = '1234567890') facets ON promos.products @> to_jsonb(facets.barcode::text) 
     UNION SELECT id, 
        (facets.weight::int * .75) AS weight -- this will return all promos, but add weight of .75 for department matches to the ones that are better matched to customer 
     FROM store_promotions promos 
     JOIN 
     (SELECT (jsonb_array_elements(department) ->> 'key') AS department, 
       (jsonb_array_elements(department) ->> 'doc_count') AS weight 
     FROM customer_transaction_facets 
     WHERE account_id = '1234567890') facets ON promos.departments @> to_jsonb(facets.department::text)) matches) AS MATCH ON p.id = match.id WHERE storeid = '637' 

回答

0
select id, weight 
from 
    store_promotions promos 
    left join (
     select 
      (jsonb_array_elements(product) ->> 'key') as key, 
      (jsonb_array_elements(product) ->> 'doc_count')::int * 1.5 as weight 
     from customer_transaction_facets 
     where account_id = '1234567890' 
     union 
     select 
      (jsonb_array_elements(department) ->> 'key') as key, 
      (jsonb_array_elements(department) ->> 'doc_count')::int * 0.75 as weight 
     from customer_transaction_facets 
     where account_id = '1234567890' 
    ) facets on 
     promos.products @> to_jsonb(facets.key::text) 
     or 
     promos.departments @> to_jsonb(facets.key::text) 
where storeid = '637'