Manse
Manse

Reputation: 38147

How to update from select with a Join

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:

I have the following tables:

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

Upvotes: 24

Views: 36135

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272426

UPDATE invoiceLine SET network = (
    SELECT label FROM network WHERE id = (
        SELECT network FROM terminal WHERE terminal.ctn = invoiceLine.ctn
    )
)

Upvotes: 5

Joe Stefanelli
Joe Stefanelli

Reputation: 135938

UPDATE invoiceLine
    INNER JOIN terminal
        ON invoiceLine.ctn = terminal.ctn
    INNER JOIN network
        ON terminal.network = network.id
    SET invoiceLine.network = network.label

Upvotes: 53

Related Questions