Random learnings and other thoughts from an unashamed geek

MySQL Limitations - Triggers and Subqueries - and Solution!

| Comments

A comment on my blog just prompted me to write a new post that hopefully helps someone out.

I have just started using triggers to improve the performance of Blog Friends. It appears that MySQL’s support of triggers is rather annoying…

One fault it has is that it will not let you update a table that the trigger was called from - you get the following error:

“#1442 - Can’t update table ‘users_users’ in stored function/trigger because it is already used by statement which invoked this stored function/trigger. ”

Now, as it happens, I was not actually updating that table, I was updating a different table, just using that as a JOIN:

UPDATE othertable JOIN users_users ON (conditions) SET othertable.value = value+27 WHERE conditions;

See - no writing to users_users at all! But still mysql blocked it.

Now, I thought, no problem, I will re-write it as a subquery:

UPDATE othertable SET value=value+27 WHERE id IN (SELECT id FROM users_users WHERE conditions) AND moreconditions;

But MySQL detects this as a DEPENDENT SUBQUERY even though it was not (my one wasn’t, at least… it only referenced NEW.values and not anything from othertable). It seems MySQL has many issues with SUBQUERYs. Well; it worked, but OMG was it slow?!! I almost had time to go and make lunch before it finished just working on 10 users… This was not good.

After a lot of moaning and no answers on #mysql on irc.freenode.net (which is unusual - normally there is people in there who know the answers to my questions!) a thought suddenly struck me…

INSERT INTO othertable(id,value) SELECT id, 27 FROM users_users WHERE conditions ON DUPLICATE KEY > UPDATE value=value+27;

Now in my application, the row should already exist, so there is no problem (and even if it didn’t the INSERT would do no harm), but if you intend to use it I suggest that you ensure that this INSERT INTO does no damage.

I hope this helps you! If it does, please leave a comment, and I will put more help!