Question

I'm using a subquery to access an alias in my where clause. This works fine as long as I only select "MIN(r.price)". When I select "*, ..." it returns an error "...duplicate column id...". Why is that? The subquery itself runs perfectly well.

Here it is:

SELECT *
FROM
(
    SELECT *, MIN(r.price) as min_price
    FROM tl_frp_presentation as p
    INNER JOIN tl_frp_object as o
        ON p.objectID = o.id
    INNER JOIN tl_tag as c
        ON c.id = o.id
        AND c.from_table = "tl_frp_object"
    LEFT JOIN tl_frp_rooms as r
        ON r.pid = o.id
    WHERE p.type = "tl_frp_object"
    GROUP BY p.id
) as inner_t
WHERE min_price >= 100

Any help is appreciated!

Was it helpful?

Solution

Just add ALIAS name to column

Try this:

SELECT *
FROM (SELECT *, MIN(r.price) AS min_price 
      FROM tl_frp_presentation AS p
      INNER JOIN tl_frp_object AS o ON p.objectID = o.id
      INNER JOIN tl_tag AS c ON c.id = o.id AND c.from_table = "tl_frp_object"
      LEFT JOIN tl_frp_rooms AS r ON r.pid = o.id
      WHERE p.type = "tl_frp_object"
      GROUP BY p.id
     ) AS inner_t
WHERE min_price >= 100;

You can also use HAVING clause to fulfill your requirement as below

SELECT *, MIN(r.price) AS min_price 
FROM tl_frp_presentation AS p
INNER JOIN tl_frp_object AS o ON p.objectID = o.id
INNER JOIN tl_tag AS c ON c.id = o.id AND c.from_table = "tl_frp_object"
LEFT JOIN tl_frp_rooms AS r ON r.pid = o.id 
WHERE p.type = "tl_frp_object"
GROUP BY p.id HAVING min_price >= 100;

OTHER TIPS

You have given the subselect an alias, which is fine!

USE it :-)

) as inner_t
WHERE inner_t.min_price >= 100

Yet better is, you don't need to wrap it into a subselect:

SELECT *, MIN(r.price) as min_price
FROM tl_frp_presentation as p
INNER JOIN tl_frp_object as o
    ON p.objectID = o.id
INNER JOIN tl_tag as c
    ON c.id = o.id
    AND c.from_table = "tl_frp_object"
LEFT JOIN tl_frp_rooms as r
    ON r.pid = o.id
WHERE p.type = "tl_frp_object"
GROUP BY p.id
HAVING min_price >= 100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top