[英]MySQL column with non-null values from other two columns
我需要知道是否有可能在MySQL中執行此操作。 有一個這樣的表:
| ID | Column1 | Column2|
+-----------------------+
| 1 | 1 | null |
| 2 | null | 2 |
| 3 | 3 | null |
獲取一個合並column1和column2的列:
| ID | Column3 |
+--------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
因此邏輯將適用於每一行,如果column1的值不同於null,則column 3將是該值,否則,它將是column 2中的值。
謝謝。
使用coalesce
獲取列的第一個非空值
select id, coalesce(column1, column2) as column3
from your_table
如果為空,則使用
SELECT ID, IFNULL(Column1,Column2) AS Column3 FROM TABLE;
如果column1為null,則使用column2
您可以使用CASE
select id, case when column1 is null then column2
when column2 is null the comumn1 end as column3
來自your_table
如果為空
select id, ifnull( column1 , column2 ) as column3
from your_table
或合並
select id, coalesce( column1 , column2 ) as column3
from your_table
您可以使用coalesce()或ifnull()函數獲得所需的輸出:
select id, coalesce(column1, column2) as column3 from yourtable
注意:如果兩個列都為空,則上面的表達式將返回空。 如果兩列都不為空,則使用column1中的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.