I recommend joy014's way otherwise you could have a look at this http://pastebin.com/9gf77Vun which does something similar as a pure php function.
There are bottlenecks in both approaches the database can only keep up so many connections per MB of RAM the php approach is not at all ACID compliant. But since I don't know how your systems scales :) this was curiosity on my side :) there are many different ways to solve this :)