MySQL if 语句子查询值

2022-01-23 00:00:00 if-statement subquery mysql

我想做这样的事情:

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

不幸的是,'as tmp' 和 returing tmp 不起作用.我怎样才能让它工作?无需重复查询:

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))

推荐答案

你可以使用 用户定义变量:

You can use User-Defined Variables:

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

SQL 小提琴

相关文章