Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to create an alias from two different fields?

Tags:

mysql

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.

like image 361
Andrew Avatar asked Jul 25 '11 18:07

Andrew


People also ask

How do you assign an alias name in two columns in SQL?

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.

What is aliasing in MySQL?

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.

Can you GROUP BY alias in MySQL?

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.

How do you multiply an alias in SQL?

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 .


2 Answers

...COALESCE(Table1.Name, Table2.Name) AS RealName...
like image 76
Joe Stefanelli Avatar answered Oct 13 '22 00:10

Joe Stefanelli


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.

like image 42
Richard Marskell - Drackir Avatar answered Oct 13 '22 00:10

Richard Marskell - Drackir