Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top