for users in the future , this is work for me:
SELECT userid, contextid FROM mdl_role_assignments WHERE contextid IN (SELECT contextid FROM mdl_role_assignments WHERE userid='3257' AND contextid IN (SELECT id from mdl_context c WHERE c.contextlevel='50')) AND roleid='5'
this query for user with teacherid (means user id) is 3257
also for get number of teachers courses you can use:
SELECT Distinct c.id as remoteid, c.fullname, ca.name as cat_name, u.id as name,COUNT(name) as number,ca.id as cat_id FROM mdl_course as c, mdl_role_assignments AS ra, mdl_user AS u, mdl_context AS ct, mdl_course_categories ca WHERE c.id = ct.instanceid AND ra.roleid =3 ANDra.userid = u.id AND ct.id = ra.contextid AND ca.id = c.category GROUP by u.lastname