1

My code:

SELECT pulpi_juegos.*, mapa.cat_id AS IDcategoria 
FROM pulpi_juegos 
INNER JOIN pulpi_categorias_mapa AS mapa ON pulpi_juegos.id=mapa.game_id 
WHERE pulpi_juegos.Estado != 1 
AND IDcategoria = 15 
ORDER BY pulpi_juegos.id DESC 
LIMIT 0,30;

Trouble is I'm getting the following error:

Unknown column 'IDcategoria' in 'where clause'

Anyone know why?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Brett
  • 19,449
  • 54
  • 157
  • 290
  • [SELECT: order of processing](http://stackoverflow.com/questions/6545664/using-case-expression-column-in-where-clause/6545685#6545685) – ypercubeᵀᴹ May 02 '12 at 09:29

4 Answers4

2

use mapa.cat_id instead of IDCategoria, because mysql executes the SELECT later.

SELECT pulpi_juegos.*, mapa.cat_id AS IDcategoria 
FROM pulpi_juegos 
INNER JOIN pulpi_categorias_mapa AS mapa ON pulpi_juegos.id=mapa.game_id 
WHERE pulpi_juegos.Estado != 1 
AND mapa.cat_id = 15 
ORDER BY pulpi_juegos.id DESC 
LIMIT 0,30;

like this order

FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
1

you can't put an alias in WHERE clause.

Use this:

SELECT pulpi_juegos.*, mapa.cat_id AS IDcategoria 
FROM pulpi_juegos 
INNER JOIN pulpi_categorias_mapa AS mapa ON pulpi_juegos.id=mapa.game_id 
WHERE pulpi_juegos.Estado != 1 
AND mapa.cat_id = 15 
ORDER BY pulpi_juegos.id DESC 
LIMIT 0,30;

Good luck.

Minucioso
  • 587
  • 1
  • 5
  • 11
1

SQL always executes the SELECT statement later then your WHERE statement. Correct me if I'm wrong but SQL executes your statement as follows:

FROM
INNER JOIN
WHERE
AND
SELECT
ORDER BY

So as you can see now, when SQL comes to your AND statement, it does not know yet that mapa.cat_id is actually represented as IDcategoria. A simple solution would be changing the IDcategoria in your AND to mapa.cat_id.
So your query will be the following:

SELECT pulpi_juegos.*, mapa.cat_id AS IDcategoria 
FROM pulpi_juegos 
INNER JOIN pulpi_categorias_mapa AS mapa ON pulpi_juegos.id=mapa.game_id 
WHERE pulpi_juegos.Estado != 1 
AND mapa.cat_id = 15 
ORDER BY pulpi_juegos.id DESC 
LIMIT 0,30;
Rick Hoving
  • 3,585
  • 3
  • 29
  • 49
1

You can not use alias in where clause , instead you should write the column name . If want to use alias in where you have to use sub query like this

SELECT * FROM (SELECT pulpi_juegos.*, mapa.cat_id AS IDcategoria 
FROM pulpi_juegos 
INNER JOIN pulpi_categorias_mapa AS mapa ON pulpi_juegos.id=mapa.game_id 
WHERE pulpi_juegos.Estado != 1  
ORDER BY pulpi_juegos.id DESC 
LIMIT 0,30) WHERE IDcategoria = 15 ;

now it will work.

Vijay
  • 1,024
  • 6
  • 18