[英]Efficient CASE Statements, SQL
Here is my query: 这是我的查询:
select col1, col2, (<a fairly complex query> as col3) from <a table>
<a fairly complex query>
may return NULL
, in which case I want to set col3
to col2
. <a fairly complex query>
可能返回NULL
,在这种情况下,我想将col3
设置为col2
。 I know I could do this with a CASE
statement: 我知道我可以使用
CASE
语句来做到这一点:
select col1, col2,
CASE WHEN (<a fairly complex query>) is NULL col2
ELSE (<a fairly complex query>) END AS col3
from <a table>
However, that approach executes <a fairly complex query>
twice. 但是,该方法执行
<a fairly complex query>
两次。 What are some options if I only want to execute <a fairly complex query>
once? 如果我只想执行一次
<a fairly complex query>
,有哪些选择?
You could use subquery and COALESCE
: 您可以使用subquery和
COALESCE
:
SELECT col1, col2, COALESCE(col3, col2) AS col3
FROM (select col1, col2, (<a fairly complex query>) as col3
from <a table>) AS sub;
Without subquery: 没有子查询:
SELECT col1, col2, COALESCE(<a fairly complex query>, col2) AS col3
FROM <a table>;
与其他答案类似,但是不需要子查询:
select col1, col2, COALESCE(<a fairly complex query>, col2) AS col3 from <a table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.