select c.id,c.title,m.id from chats as c join messages as m on m.chat_id=c.id where date(sent_on)<'2012-06-23' and substr(c.title,-1,1)='x' order by c.id asc,m.id asc