高效的CASE语句,SQL

时间:2018-03-16 20:36:28

标签: mysql sql case

这是我的问题:

select col1, col2, (<a fairly complex query> as col3) from <a table>

<a fairly complex query>可能会返回NULL,在这种情况下,我想将col3设置为col2。我知道我可以用CASE语句来做到这一点:

select col1, col2, 
CASE WHEN (<a fairly complex query>) is NULL col2
ELSE (<a fairly complex query>) END AS col3 
from <a table>

但是,该方法执行<a fairly complex query>两次。如果我只想执行<a fairly complex query>一次,有哪些选项?

2 个答案:

答案 0 :(得分:4)

您可以使用子查询和COALESCE

SELECT col1, col2, COALESCE(col3, col2) AS col3
FROM (select col1, col2, (<a fairly complex query>) as col3 
      from <a table>) AS sub;

没有子查询:

SELECT col1, col2, COALESCE(<a fairly complex query>, col2) AS col3
FROM <a table>;

答案 1 :(得分:0)

与其他答案类似,但不需要子查询:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /* create textview */
        TextView tv = new TextView(this);
        tv.setBackgroundColor(0xff12dd12);
        tv.setText("dynamic textview");

        /* create button */
        Button btn = new Button(this);
        btn.setText("dynamic btn");
        btn.setBackgroundColor(0xff12dd12);

        TableRow.LayoutParams trparams = new TableRow.LayoutParams(0, TableRow.LayoutParams.MATCH_PARENT);
        trparams.weight = 3;
        tv.setLayoutParams(trparams);
        trparams.weight = 2;
        trparams.rightMargin = 10;
        btn.setLayoutParams(trparams);

        TableLayout tableLayout = (TableLayout) findViewById(R.id.layoutTable);

        LinearLayout.LayoutParams tableRowParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        /* create a table row */
        TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(tableRowParams);

        /* add views to the row */
        tableRow.addView(tv);
        tableRow.addView(btn);

        /* add the row to the table */
        tableLayout.addView(tableRow);
    }