Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update from select with a Join

Tags:

How can I update a table that is also present in a subquery? Do I have to do it in 2 stages? (create a temporary table - put the selected data in it and then update the final table)

I am trying to update the invoiceLine table with the label of the network for each CTN.

The end result would be:

  • invoiceLine

    ctn       network
    1234      network1
    2345      network2
    3456      network1
    

I have the following tables:

  • invoiceLine

    ctn       network
    1234      null
    2345      null
    3456      null
    
  • terminal

    ctn       network
    1234      1
    2345      2
    3456      1
    
  • network

    id        label
    1         network1
    2         network2
    

I can run a select but I'm not sure how to update with a join:

update invoiceLine 
inner join terminal on terminal.ctn = invoiceLine.ctn 
set invoiceLine.network = 
(
  select network.label 
  from invoiceLine 
  inner join terminal on terminal.ctn = invoiceLine.ctn 
  inner join network on network.id = terminal.network
) 
where invoiceLine.ctn = terminal.ctn

but MySQL throws a

Error Code: 1093. You can't specify target table 'invoiceLine' for update in FROM clause

like image 429
Manse Avatar asked Oct 27 '11 13:10

Manse


People also ask

Can you do an update with a join?

SQL UPDATE JOIN could be used to update one table using another table and join condition.

Can we do an update from a SELECT statement?

The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.

Can we use SELECT statement in join?

So, an SQL Join clause in a Select statement combines columns from one or more tables in a relational database and returns a set of data. The From is also an essential part of the Select statement and this is where it's specified which table we're pulling data from.

Can we use left join in update query?

We can use the Update statement with Left Join as well, and it updates the records with NULL values. As highlighted earlier, we cannot use a single Update statement for updating multiple columns from different tables.


2 Answers

UPDATE invoiceLine
    INNER JOIN terminal
        ON invoiceLine.ctn = terminal.ctn
    INNER JOIN network
        ON terminal.network = network.id
    SET invoiceLine.network = network.label
like image 74
Joe Stefanelli Avatar answered Sep 19 '22 13:09

Joe Stefanelli


UPDATE invoiceLine SET network = (
    SELECT label FROM network WHERE id = (
        SELECT network FROM terminal WHERE terminal.ctn = invoiceLine.ctn
    )
)
like image 43
Salman A Avatar answered Sep 18 '22 13:09

Salman A