27

I have a query that looks something like that:

SELECT a, b, c,
    (SELECT d from B limit 0,1) as d
FROM A
WHERE d >= 10

I get the result that I want when I run the query without the whereclause but when I add the where clause the query fails.

Does anyone have a suggestion how to solve that?

2 Answers 2

60

You can't use a column alias in WHERE clause.

So you either wrap your query in an outer select and apply your condition there

SELECT * 
  FROM
(
  SELECT a, b, c,
    (SELECT d FROM B LIMIT 0,1) d
  FROM A
) q
 WHERE d >= 10

or you can introduce that condition in HAVING clause instead

SELECT a, b, c,
    (SELECT d FROM B LIMIT 0,1) d
  FROM A
HAVING d >= 10

Yet another approach is to use CROSS JOIN and apply your condition in WHERE clause

SELECT a, b, c, d
  FROM A CROSS JOIN 
(
  SELECT d FROM B LIMIT 0,1
) q
 WHERE d >= 10

Here is SQLFiddle demo for all above mentioned queries.

Sign up to request clarification or add additional context in comments.

3 Comments

very helpful, +1 for mentioning the very ufseful SqlFiddle:)
Good that you mentioned HAVING, as it's been always thought to be useful only with GROUP BY.
What are the impacts on performance when using query wrapping vs. the having clause vs. cross join?
0

Is this what you want?

SELECT a, b, c,
    B.d
FROM A, (SELECT d from B limit 0,1) B
WHERE B.d >= 10 

3 Comments

Nope, because if for example d is not >= 10 this column would simply be empty but I want if the where clause doesn't match that the entire row will not be displayed
@Chris is there any realtion between TableA and TalbeB ?
Sorry, I have not environment to test. I changed the sql. How about this time?

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.