Unable to commit query SELECT * FROM sponsors3 as s LEFT JOIN (SELECT id as s2c_id, sponsor_id, category_id FROM sponsor2cat) as s2c ON s.id=s2c.sponsor_id LEFT JOIN (SELECT id as spId,category,front,order_by FROM sponsor_cats3 ) as spCat ON spCat.spId=s2c.category_id AND spCat.front=1 WHERE ( (s.published=1 AND s.no_publish) OR (s.date_published<'2017-07-25 23:59' AND !s.no_publish)) AND s.step=3 AND (s.no_expire=1 OR s.expiredate>'2017-07-25 23:59') AND s.authorized=1 AND NOT EXISTS (select front from sponsor_cats3 WHERE front=0 and sponsor_cats3.id=s2c.category_id) GROUP BY s.id ORDER BY spCat.order_by, s.order_by