0

I've used This Stack for my query:

UPDATE breads
SET id_supply = (SELECT max(id) FROM supply)
WHERE id = (SELECT MAX(id) FROM breads)

I have added a new record into supply. Now I want my last bread to have the id_supply of the last supply.id

#1093 - Table 'breads' is specified twice, 
both as a target for 'UPDATE' and as a separate source for data
Halfacht
  • 924
  • 1
  • 12
  • 22

2 Answers2

1

In MySQL, you cannot refer to the table being updated subsequently in the query (well, without a little hack).

Instead, use order by and limit:

UPDATE breads b
    SET b.id_supply = (SELECT max(s.id) FROM supply s)
    ORDER BY b.id DESC
    LIMIT 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

If the answer given by @Gordon is not working, then I guess you should try a little hack he's talking about in his answer.

Although, Gordon's query works fine with my Test data, but if it's not working for you then try the following query:

UPDATE breads
SET id_supply = (SELECT max(id) FROM supply)
WHERE id = (SELECT MAX(br.id) FROM (select *from breads) br);

Click here for the Demo

Hope it helps!

Note: If this query won't work too, then you should add the Schema and Sample data into your question.

Harshil Doshi
  • 3,497
  • 3
  • 14
  • 37