使用MySQL如果first为空,请选择第二列值?

时间:2019-02-05 10:51:59

标签: mysql

如果第一列的值为空,如何选择第二列的值。

例如:表格预订中包含类似的记录

id | sold_price | contract_price
---------------------------------
1  | 10000      | 150000
---------------------------------
2  |            | 20000

我正在寻找类似mysql的查询

    Select SUM
           (If (bookings.sold_price !=NULL) 
            Else bookings.contract_price)
    FROM bookings 
    Where id=2

有什么办法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用null的情况

Select sum( case when bookings.sold_price  is null 
         then bookings.contract_price else bookings.sold_price  end)
from my_table  
where id = 2 

或者在mysql中,您可以使用ifnull

Select sum( ifnull(bookings.sold_price , bookings.contract_price) )
from my_table  
where id = 2 

答案 1 :(得分:1)

使用coalesce()函数

Select SUM(coalesce(bookings.sold_price,bookings.contract_price)) 
from tablename
where id=2

答案 2 :(得分:1)

尝试

SELECT 
    SUM(COALESCE(sold_price, contract_price))
FROM
    table_bookings
WHERE
    id = 2;

coalesce返回列表中的第一个非空值。

相关问题