Combine two tables into a new one so that select rows from the other one are ignored

前端 未结 2 1869
执笔经年
执笔经年 2020-12-12 03:57

I have two tables that have identical columns. I would like to join these two tables together into a third one that contains all the rows from the first one and from the sec

相关标签:
2条回答
  • 2020-12-12 04:16

    Change UNION ALL to just UNION and it should return only unique rows from each table.

    0 讨论(0)
  • 2020-12-12 04:21

    UNION simply doesn't do what you describe. This query should:

    CREATE TABLE AS 
    SELECT date, location_code, product_code, quantity
    FROM   transactions_kitchen k
    
    UNION  ALL
    SELECT h.date, h.location_code, h.product_code, h.quantity
    FROM   transactions_admin h
    LEFT   JOIN transactions_kitchen k USING (location_code, date)
    WHERE  k.location_code IS NULL;
    

    LEFT JOIN / IS NULL to exclude rows from the second table for the same location and date. See:

    • Select rows which are not present in other table

    Use CREATE TABLE AS instead of SELECT INTO. The manual:

    CREATE TABLE AS is functionally similar to SELECT INTO. CREATE TABLE AS is the recommended syntax, since this form of SELECT INTO is not available in ECPG or PL/pgSQL, because they interpret the INTO clause differently. Furthermore, CREATE TABLE AS offers a superset of the functionality provided by SELECT INTO.

    Or, if the target table already exists:

    INSERT INTO transactions_combined (<list names of target column here!>)
    SELECT ...
    

    Aside: I would not use date as column name. It's a reserved word in every SQL standard and a function and data type name in Postgres.

    0 讨论(0)
提交回复
热议问题