为什么这个SQL Query会返回错误?

时间:2014-01-08 09:28:00

标签: mysql sql select group-by having

我正在使用子查询来访问where子句中的别名。 只要我选择“MIN(r.price)”,这就可以正常工作。当我选择“*,...”时,它会返回错误“...重复列ID ...”。这是为什么?子查询本身运行得非常好。

这是:

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

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:0)

只需将 ALIAS 名称添加到列

即可

试试这个:

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;

您还可以使用 HAVING 子句来满足您的要求,如下所示

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;

答案 1 :(得分:0)

你给了subselect一个别名,这很好!

使用它: - )

) as inner_t
WHERE inner_t.min_price >= 100

更好的是,你不需要把它包装成一个子选择:

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