2015-07-21 89 views
1

爲PostgreSQL調整以下SQL的最佳方式是什麼?這似乎代價很高?將創建臨時表提供最佳的成本?在PostgreSQL中調整查詢

UPDATE table1 
SET id = qry.crmId 
FROM (
    SELECT b.id AS crmId, a.row 
    FROM table1 AS a INNER JOIN table2 AS b ON lower(a.email) = lower(b.email) AND b.id = (
       SELECT MIN(id) 
       FROM table2 
       WHERE email = b.email AND email IS NOT NULL AND 
       created = (
          SELECT MIN(created) 
          FROM table2 
          WHERE email = b.email 
          ) 
       LIMIT 1 
       ) 
    WHERE a.email IS NOT NULL AND b.id IS NOT NULL AND a.id IS NULL 
    ) AS qry 
WHERE table1.row = qry.row; 
+0

http://stackoverflow.com/tags/postgresql-performance/info –

+0

嚴格地說,如果沒有看到表格的定義,這個問題就不能回答。我們不知道'row'是否是唯一的列或哪些列可以是NULL。最好的查詢還取決於數據分佈(兩個表中是否都是大多數id?)等等。這個問題最少需要解釋查詢的目的是什麼。無論哪種方式,目前接受的答案是*不等同於您的查詢。沒有'table2'和'b.id IS NOT NULL'被區別對待。 –

回答

0

如果短語查詢是這樣的:

update table1 t11 
    set id = (select id 
       from table1 t12 
       where t12.email = t11.email and 
        t12.id is not null 
       order by t12.created 
       limit 1 
      ) 
    where id is null and email is not null; 

然後,它可以採取table1(id)table1(email, created, id)優勢指標。

您可能想要添加一個檢查,例如and exists (select 1 from table1 t12 where t12.email = t11.email and t12.email is not null and t12.id is not null)

+0

需要將其他檢查添加到內部查詢嗎? – user1595858

+0

@ user1595858。 。 。不,對外部查詢。 –