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

如果第一列使用MySQL为空,请选择第二列值?,mysql,Mysql,如果第一列值为空,如何选择第二列的值 例如:表格预订包含以下记录 id | sold_price | contract_price --------------------------------- 1 | 10000 | 150000 --------------------------------- 2 | | 20000 我正在寻找一些类似mysql的查询 Select SUM (If (bookings.sold_pri

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

例如:表格预订包含以下记录

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

有什么方法可以做到这一点吗?

可以在为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 
使用
coalesce()
函数

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

SELECT 
    SUM(COALESCE(sold_price, contract_price))
FROM
    table_bookings
WHERE
    id = 2;
coalesce
返回列表中的第一个非空值