I have a query that is joining two tables. I would like to be able to create an alias that allows the value to default to a different field when the original field is null. Here is an example:
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
I am getting an "unknown column in field list" error when I try doing this.
Update: Turns out my unknown column error was due to something else. The MySQL coalesce function worked great for this.
Yes, you can alias multiple columns at a time in the same query. It is advisable to always include quotes around the new alias. Quotes are required when the alias contains spaces, punctuation marks, special characters or reserved keywords. It is simply more convenient to always include quotes around the new alias.
SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query. An alias is created with the AS keyword.
A column alias cannot be used in a SELECT, WHERE, GROUP BY or HAVING clause due to the order of execution. You must refer to the original column name.
All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query. You can give this result an alias with the AS keyword; in our example, we gave the multiplication column an alias of total_price .
...COALESCE(Table1.Name, Table2.Name) AS RealName...
Try this instead:
(case when Table1.Name IS NULL then Table2.Name else Table1.Name end) AS 'RealName'
Edit
And also in your Order by, change it to:
order by (case when Table1.Name IS NULL then Table2.Name else Table1.Name end) asc
Edit 2
As others have stated, you can also use coalesce(Table1.Name, Table2.Name)
but I believe the error is still because you're referencing the aliased column in the order by
. With either method, just put the code you're aliasing in the order by
and it should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With