6

The Query:

UPDATE nominees SET votes = ( SELECT votes
FROM nominees
WHERE ID =1 ) +1

The Error:

You can't specify target table 'nominees' for update in FROM

Not sure whats wrong there based on the error, this is the first time im tryin to incriment a column inline i guess you can call it. So I am obvioulsy doing something wrong but dont know how to fix it.

chris
  • 36,115
  • 52
  • 143
  • 252

1 Answers1

13

Your UPDATE query is missing any WHERE clause so even if MySQL had allowed it then the effect would be to find the votes value for the ID =1 row add 1 to it then update all rows in the table with the result.

I suspect that was not the desired behaviour. To increment the column value you just need to do

UPDATE nominees 
SET votes = votes +1
WHERE ID =1 

Just in case you do want the other behaviour you would need to do

UPDATE nominees
SET    votes = (select votes + 1
                FROM   (SELECT votes
                        FROM   nominees
                        WHERE  ID = 1) T)  

This wrapping into a derived table avoids the You can't specify target table 'nominees' for update in FROM error you were getting.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • 2
    thats the ticket right there!.. maybe im getting to tired for this $*(# tonight.. makin simple mistakes all over the place. – chris Sep 03 '11 at 11:06
  • what the T for? at the end of the Edit? – chris Sep 03 '11 at 11:23
  • 2
    @chris - It is just an arbitrary table alias for the subquery / derived table. Optionally it could have said `) AS T`. See http://dev.mysql.com/doc/refman/5.6/en/from-clause-subqueries.html for more on these. – Martin Smith Sep 03 '11 at 11:24
  • maybe you can help me with one more question I have.. I thought I had found the answer prior but I was wrong. – chris Sep 03 '11 at 11:29
  • http://stackoverflow.com/questions/7292502/mysql-failed-attempt-at-getting-posts-from-last-24hr-and-last-60-min is the question in question :) – chris Sep 03 '11 at 11:29
  • Can't see any obvious reason why that shouldn't work. Are you sure that the query actually being executed is exactly that? i.e. have you tried running that exact query directly against your DBMS as I see from your edit history that the query is being created through code. – Martin Smith Sep 03 '11 at 11:34