it should be noted that MySQL does not implement the SQL:1999 feature for CTEs
Wow! Didn't know that at all. I just assumed.... Thank you for the heads up!
A quick search shows people doing this with functions. It's likely better than doing it in another layer, but certainly not as good as using straight SQL (for both performance and security reasons.)