我有一個連接兩個表的查詢。我希望能夠創建一個別名,當原始字段爲空時,允許該值默認爲不同的字段。這裏是一個例子:MySQL:如何從兩個不同的字段創建別名?
select
Table1.Name,
Table2.Name,
(case when Table1.Name then Table2.Name else Table1.Name end) AS 'RealName'
from Table3
left join Table1 on Table1.ID = Table3.Table1_ID
left join Table2 on Table2.ID = Table3.Table2_ID
order by `RealName` asc
當我嘗試這樣做時,出現「字段列表中未知列」錯誤。
更新:原來我的未知列錯誤是由於其他原因。 MySQL coalesce function爲此很好。通過
(case when Table1.Name IS NULL then Table2.Name else Table1.Name end) AS 'RealName'
編輯
同時也可在您的訂單,將其更改爲:
@ain:當然可以。 [http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators。 HTML#function_coalesce) –