问题
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))
回答1:
You can use User-Defined Variables:
SELECT IF(
@val:=(SELECT something FROM table1) > 0,
@val,
(SELECT bla FROM table2)
)
SQL Fiddle
回答2:
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
来源:https://stackoverflow.com/questions/17723808/mysql-if-statement-subquery-value