SQL Query (python + MySQLdb)

This version works and takes into account the weird cases we discussed
today. I'll fix up RE later (I left my python book that I need as a
reference at work!)