update query with join on two tables

前端 未结 5 1500
情歌与酒
情歌与酒 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
    

提交回复
热议问题