Query Optimization Based on the Automata Theory