0

I want to do something like this:

SELECT IF((SELECT something FROM table) AS tmp) > 0, tmp, (SELECT bla FROM oter_table))

Unfortunately the 'as tmp' and returing the tmp is not working. How can I get this to work? without doing repeating the query:

SELECT IF((SELECT something FROM table) > 0, (SELECT something FROM table), (SELECT bla FROM oter_table))
3
  • 1
    Have you read up on the JOIN statement? Commented Jul 18, 2013 at 12:46
  • The actual situation is a bit more complicated, therefore I would like to know how I could fix the above situation (without joins). Commented Jul 18, 2013 at 12:50
  • Maybe don't use a RDBMS? Commented Jul 18, 2013 at 13:00

2 Answers 2

4

You can use User-Defined Variables:

SELECT IF(
          @val:=(SELECT something FROM table1) > 0, 
          @val, 
          (SELECT bla FROM table2)
       )

SQL Fiddle

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

Comments

0
SELECT IF( (SELECT something AS tmp FROM first_table) > 0, tmp, (SELECT bla FROM other_table) )

EDIT This is not going to work. You need to quantify the selection somewhere with a "WHERE" clause, like so:

SELECT IF( (SELECT something FROM first_table) > 0, (SELECT something FROM first_table), (SELECT something_else FROM second_table) ) FROM first_table WHERE something = 45 

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.