views:

83

answers:

2

I need to do subquery in subquery what causes "Unknown column 't1.product_id' in 'where clause'". It's on line 7. in my example. How to solve this problem?

SELECT *,product_id id,
    (SELECT GROUP_CONCAT (value ORDER By `order` ASC SEPARATOR ', ') 
    FROM (
        SELECT `order`,value 
        FROM slud_data 
        LEFT JOIN slud_types ON slud_types.type_id=slud_data.type_id 
        WHERE slud_data.product_id = t1.product_id 
          AND value!='' AND display=0 
        LIMIT 3
    ) tmp) text
FROM slud_products t1 
WHERE 
    now() < DATE_ADD(date,INTERVAL +ttl DAY) AND activated=1
    ORDER BY t1.date DESC

This question continues from http://stackoverflow.com/questions/3378324/limit-ignored-in-query-with-group-concat

A: 

Subqueries work "inside out" - just like order of operations in arithmetic.

To reference t1.product_id, you're going to need to have a reference to that table on the innermost subquery:

    SELECT `order`
         , `value`
      FROM slud_data 
INNER JOIN slud_products_t1 ON slud_data.product_id = t1.product_id
 LEFT JOIN slud_types ON slud_types.type_id = slud_data.type_id 
     WHERE value != '' AND display = 0 
     LIMIT 3
AvatarKava
Yes, that gives me t1.product_id, but it's always first row from slud_products not current. That results in `text` always the same for all rows.
Māris Kiseļovs
Can you give the db structure and try to describe the problem you're solving? There is probably a much easier query without the extra subqueries nested in.
AvatarKava
+1  A: 

Use a derived table/inline view, and table aliases:

  SELECT product_id AS id,
         GROUP_CONCAT (y.value ORDER BY y.`order`) 
    FROM slud_products t1 
    JOIN (SELECT sd.product_id, 
                 sd.value,
                 sd.`order`
            FROM SLUD_DATA sd 
       LEFT JOIN slud_types ON slud_types.type_id = slud_data.type_id 
           WHERE value! = '' 
             AND display = 0) y ON y.product_id = t1.product_id 
                               AND y.order <= 3
   WHERE now() < DATE_ADD(date,INTERVAL +ttl DAY) 
     AND activated = 1
GROUP BY product_id
ORDER BY t1.date DESC
OMG Ponies