I'm not sure exactly why it works
It works because the user defined variables need to be initialized. Because variables are session specific they are 'retained' when using MySQL workbench. You should notice that your original query does not work in MySQL workbench on the first run but then works on subsequent runs. Using DBD you are creating a new session each time so variables never get initialized. You could use your original query by adding a set command before the execute
$dbh->do('SET @recent_post_rank := 0, @prev_discussion := 0');
poj