MySQL if statement subquery value

不打扰是莪最后的温柔 提交于 2019-12-14 03:28:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!