Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown column in subquery where clause

Tags:

mysql

subquery

I'm having a problem in the where clause of my INNER JOIN subquery. I'm receiving a unknown column error for M.idMembre. I've tried using the table name instead of the alias but I get the same issue. I've also tried removing the WHERE clause from the subquery and adding this condition in the ON clause after the subquery. However, I'm having the same issue either way. I feel it's something obvious I'm missing here.

SELECT DISTINCT M.`idMembre` ,  `couponsTypes`.`maxCouponType` 
FROM membres AS  `M` 
INNER JOIN (
SELECT idMembre, MAX( coupons.`idType` ) AS  `maxCouponType` 
FROM coupons
WHERE coupons.`idMembre` = M.`idMembre` 
GROUP BY idMembre
) AS  `couponsTypes` 
ON M.`idMembre` = couponsTypes.`idMembre`
ORDER BY maxCouponType DESC 

Let me know if you need more information.

like image 866
oliboon Avatar asked Dec 18 '12 21:12

oliboon


People also ask

Can I use subquery in where clause?

You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause, FROM clause. Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator.

Is subquery not allowed in where clause?

Subqueries must appear on the right hand side of an expression. Nested subqueries are not supported. Only one subquery expression is allowed for a single query. Subquery predicates must appear as top level conjuncts.


2 Answers

You are not allowed to reference outer tables in a subquery in a join clause. One way to solve this is by doing a group by in the subquery based on the join condition:

SELECT DISTINCT M.`idMembre`, `couponsTypes`.`maxCouponType`
FROM membres AS `M` 
INNER JOIN
(SELECT idMembre, MAX(coupons.`idType`) AS `maxCouponType`
   FROM coupons
   GROUP BY idmembre
) `couponsTypes`
ON couponstypes.idMembre = M.idMember
ORDER BY maxCouponType DESC

But, you don't need the membres table at all. Although referenced in the outer select, it is equivalent to the member id in the coupons type table. So, you can write your query as:

SELECT idMembre, MAX(coupons.`idType`) AS `maxCouponType`
FROM coupons
GROUP BY idmembre
ORDER BY 2 DESC

This is probably the simplest and most efficient way formulation.

like image 155
Gordon Linoff Avatar answered Oct 06 '22 22:10

Gordon Linoff


Your subquery does not have access to the tables in the outer query. That is, the membres table (aliased as M) is not available at the time that the couponsTypes subquery is evaluated.

However, such a subquery should not be necessary in this case; you merely need to join the tables directly and group the result:

SELECT   idMembre, MAX(coupons.idType) AS maxCouponType
FROM     membres JOIN coupons USING (idMembre)
GROUP BY idMembre
ORDER BY maxCouponType DESC
like image 44
eggyal Avatar answered Oct 06 '22 20:10

eggyal