Mysql rewrite

This is now pretty much at the point of being equal with the original and is ready to be pulled in over the top!