4

I have this select statement working fine:

SELECT 
  pre, dict.char, post, score
  , (SELECT @res := MatchPre(pre, 'test') AS var) AS mpre 
FROM dict;

It returns all of the data properly, with the result from MatchPre in a column labeled "mpre". However, I want to only get results where mpre > 0. So, logically, I tried this:

SELECT 
  pre, dict.char, post, score
  , (SELECT @res := MatchPre(pre, 'test') AS var) AS mpre 
FROM dict 
WHERE mpre > 0;

But to no avail. I've tried swapping "WHERE mpre > 0" with "WHERE @res > 0", "WHERE @res.mpre > 0", "WHERE mpre.@res > 0", etc, but it either throws an error or returns an empty result set despite the original where-less query giving rows with mpre values greater than 0.

What is the correct syntax for this?

1 Answer 1

6
SELECT 
  pre, dict.char, post, score
  , (SELECT @res := MatchPre(pre, 'test') AS var) AS mpre 
FROM dict 
HAVING mpre > 0;

You cannot use aliases in a where clause.
You will have to use a having clause or put the select with the alias inside another outer select.

This is because when the where clause is run, the alias is not yet evaluated.
The having run after all the select,where, group by, from and joins are finished and does not suffer this limitation.
Having cannot use an index though.
If you want to use an index use a sub-select.

SELECT sub.* FROM
  (SELECT 
     pre, dict.char, post, score
     , (SELECT @res := MatchPre(pre, 'test') AS var) AS mpre 
   FROM dict ) sub
 WHERE sub.mpre > 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.