If I understand correctly, you can do this in a single database query.
SELECT q.* FROM questions q LEFT JOIN ( SELECT e.id FROM exams e LEFT JOIN questions q ON (e.id = q.exam_id) WHERE level = ? AND flag = ? AND q.id IS NOT NULL ORDER BY RAND() LIMIT 1 ) i ON (q.exam_id = i.id) WHERE i.id = q.exam_id
You join in a subquery as a table in your query. The subquery selects a single random item from the exams table, and itself joins in the questions table, to make sure that some questions exist. Demo is here: http://sqlfiddle.com/#!9/b394af/1