update query with join on two tables

前端 未结 5 1488
情歌与酒
情歌与酒 2020-12-18 18:13

I have customer and address tables.

Query:

SELECT *
FROM addresses a,
     customers b
WHERE a.id = b.id

相关标签:
5条回答
  • 2020-12-18 18:52

    Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like

    Update addresses
    Set cid = (
                Select c.id
                From customers As c
                where c.id = a.id
                )
    Where Exists    (
                    Select 1
                    From customers As C1
                    Where C1.id = addresses.id
                    )
    

    However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:

    Update addresses
    Set cid = c.id
    From addresses As a
        Join customers As c
            On c.id = a.id
    
    0 讨论(0)
  • 2020-12-18 18:57
    update addresses set cid=id where id in (select id from customers)
    
    0 讨论(0)
  • 2020-12-18 19:02

    Try this one

    UPDATE employee 
    set EMPLOYEE.MAIDEN_NAME = 
      (SELECT ADD1 
       FROM EMPS 
       WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
    WHERE EMPLOYEE.EMP_CODE >='00' 
    AND EMPLOYEE.EMP_CODE <='ZZ';
    
    0 讨论(0)
  • 2020-12-18 19:04

    Using table aliases in the join condition:

    update addresses a
    set cid = b.id 
    from customers b 
    where a.id = b.id
    
    0 讨论(0)
  • 2020-12-18 19:06

    this is Postgres UPDATE JOIN format:

    UPDATE address 
    SET cid = customers.id
    FROM customers 
    WHERE customers.id = address.id
    

    Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

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