Search code examples
sqljoinpgadminpostgresql-13

SQL Join with multiple conditions


I need a query to fill the column netto from table test with values from lv from table co when two conditions (test.sp= co.sp) AND (test.ver= co.ver) are given

Table test:

sp ver netto
A X Null
B Y Null
C Z Null

Table co:

sp ver lv
A X F
B Y G
C Z H

I've tried this query, but it doesn't work.

UPDATE test
SET test.netto= co.lv
FROM test
JOIN co ON (test.sp= co.sp) AND (test.ver= co.ver);

Result should be (table test):

sp ver netto
A X F
B Y G
C Z H

I get the following error message:

Error : ERROR: table name specified more than once

Solution

  • Your update statement was close.

    update test
       set netto = co.lv
      from co
     where test.sp = co.sp
       and test.ver = co.ver
    

    Output of select * from test:

    A   X   F
    B   Y   G
    C   Z   
    

    Where test and co were set up as:

    create table test (
      sp varchar(10), 
      ver varchar(10), 
      netto varchar(10)
      );
    
    insert into test values 
    ('A','X',''),
    ('B','Y',''),
    ('C','Z','');
    
    
    create table co (
      sp varchar(10), 
      ver varchar(10), 
      lv varchar(10)
      );
    
    insert into co values 
    ('A','X','F'),
    ('B','Y','G'),
    ('K','Z','H);