将来自查询的非重复值插入另一个表

时间:2019-03-05 10:03:17

标签: sql postgresql

我有以下查询,它向我返回了cookie_hash,crdate,account_uuid和action列。

SELECT DISTINCT ON (cookie_hash) event.cookie_hash, event.crdate, event.account_uuid, event.action
FROM event
WHERE cookie_hash IN (SELECT community_signup.cookie_hash FROM community_signup) AND 
event.action = 'signup'
ORDER BY cookie_hash, crdate DESC;

然后我有另一个表community_signup,其中的填充列cookie_hash和空列crdate和account_uuid。

如何用cookie_hash的对应值填充table2中的空列?

2 个答案:

答案 0 :(得分:0)

我希望这对您有用。

 UPDATE A
    SET A.crdate =B.crdate,
    A.account_uuid = B.account_uuid
    FROM community_signup AS A
    INNER JOIN 
    (
    SELECT Distinct cookie_hash, crdate, account_uuid, [action]
    FROM [event] WHERE cookie_hash IN (SELECT community_signup.cookie_hash FROM community_signup) AND 
    event.action = 'signup'
    ORDER BY cookie_hash, crdate DESC
    )AS B
    ON A.cookie_hash = B.cookie_hash

答案 1 :(得分:0)

FROM中使用UPDATE子句。 Postgres语法如下:

UPDATE community_signup cs
    SET crdate = e.crdate,
        account_uuid = e.account_uuid
FROM (SELECT DISTINCT ON (e.cookie_hash) e.cookie_hash, e.crdate, e.account_uuid, e.action
      FROM event e
      WHERE e.cookie_hash IN (SELECT cs.cookie_hash
                              FROM community_signup cs
                             ) AND 
            e.action = 'signup'
      ORDER BY e.cookie_hash, e.crdate DESC         
     ) 
WHERE e.cookie_hash = cs.cookie_hash;

请注意,我添加了表别名,因此查询更易于编写和阅读。

此外,IN过滤器并不是真正必需的。外部的WHERE也可以处理。