0

I really regret having to ask -- but I have searched all evening and have not found a solution that resolves my question. Please excuse me.

I have an update I am trying to run on a table that references the same table. I'm pretty sure I have to go about a rename, but I can't get it function correctly. Any help would be appreciated.

Here is my query, it is accepted but it doesn't modify the table.

update parts 
set price = price * .85 
where price > (select avg(price));

Thanks in advance.

0

2 Answers 2

2

Use join:

update parts p join
       (select avg(price) as avgprice from parts) pp
       on p.price > pp.avgprice
    set p.price = p.price * 0.85 ;

In an update or delete statement, MySQL does not allow you to reference the table(s) being modified in the rest of the query. It is the only database with this limitation, but it also provides the join syntax as an alternative method.

Sign up to request clarification or add additional context in comments.

1 Comment

You sir, are my hero. Thank you.
0

Your subquery needs a FROM statement.

update parts p1 
set p1.price = p1.price * .85 
where p1.price > (select avg(p2.price) from parts p2);

Without the 'from' it uses your current column, and since you are not grouping by anything, it does average of the current column's value, which is itself, and by definition is not greater than itself.

Also, give the table names aliases so the db doesn't mix them up.

3 Comments

Thank you for the response. I have attempted your suggestion and it returns this error: ERROR 1093 (HY000): You can't specify target table 'parts' for update in FROM clause
Thank you again. Same error: ERROR 1093 (HY000): You can't specify target table 'p1' for update in FROM clause
The alias need to be outside of the subquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.