Invalid query: select * from (select st.sponsor_id, count(st.sponsor_id) as cnt from sponsor_tags st where st.tag_id in ('S',''','T') group by st.sponsor_id) as x inner join (select count(st.tag_id) as total, st.sponsor_id from sponsor_tags st group by st.sponsor_id) as y on x.sponsor_id=y.sponsor_id and y.total=x.cnt and y.total='3' inner join sponsor s on x.sponsor_id=s.sponsor_id and s.sponsor_active='1' You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'T') group by st.sponsor_id) as x inner join (select count(st.tag_id) as total, s' at line 1