3

I am writing following query in mysql, but it returning 0 rows

select * from (select col1 as mycol from tbl) temp where temp.mycol = 5

but the following query returning 4 rows

select col1 as mycol from tbl where col1 = 5

what is wrong with 1st query?

Andomar
  • 232,371
  • 49
  • 380
  • 404
Mandeep Singh
  • 2,016
  • 7
  • 19
  • 32

3 Answers3

0

In answer to your problem in your comment:

i am trying with little change but it not working any suggesion??? select * from (select col1 as 'my col' from tbl) temp where 'temp.my col' = 5 – Mandeep Singh May 30 at 7:48

The problem you are having here is that MySQL is looking for a column called 'temp.my col' but what you really want is the column called my col in the table temp So you need to do this:

select * from (select col1 as `my col` from tbl) temp where `temp`.`my col` = 5
chrislondon
  • 12,487
  • 5
  • 26
  • 65
0

If you want to refer to an Alias (in MySQL) you need to use HAVING instead of WHERE. Your second line works because you are not referring to the alias, but the first statement fails because you are referring to an alias with WHERE.

Griknok
  • 384
  • 2
  • 13
0

It works fine at my End. But I search for your problem and get this thread:

Using column alias in WHERE clause of MySQL query produces an error

MySQL also states this : http://dev.mysql.com/doc/refman/5.6/en/problems-with-alias.html

Now I also confused why it works for me?

Community
  • 1
  • 1
Aman Aggarwal
  • 17,619
  • 9
  • 53
  • 81