通过内部选择的结果过滤MySQL结果集

时间:2013-02-15 16:27:19

标签: mysql sql select join

我有一个执行内部SELECT的MySQL语句,并将结果作为伪列返回。我想在我的WHERE子句中使用这个伪列的结果。我当前的SQL语句如下所示:

SELECT
    product.product_id,
    product.range_id,
    product.title,
    product.image,
    product.image_text,
    product.friendly_url,
    attribute.comfort_grade_id,
    category.category_id,
    category.category AS category_name,
    category.friendly_url AS category_friendly_url,
    (SELECT price_now FROM product_bedding_sizes AS size WHERE size.product_id = product.product_id ORDER BY size.price_now ASC LIMIT 1) AS price
FROM
    products AS product
LEFT JOIN
    categories AS category ON product.category_id = category.category_id
LEFT JOIN
    product_bedding_attributes AS attribute ON product.product_id = attribute.product_id
$where
$order
LIMIT
    ?,?

但是,运行查询时出现以下错误消息:

  

#1054 - 'where子句'中的未知列'价格'

如何解决这个问题,并在我的price子句中实际使用WHERE的值?

3 个答案:

答案 0 :(得分:3)

WHERE子句在SELECT子句之前计算,因此它不会说别名。您必须通过外部查询中的WHERE子句执行过滤,如下所示:

SELECT *
FROM
(
    SELECT
        product.product_id,
        product.range_id,
        product.title,
        product.image,
        product.image_text,
        product.friendly_url,
        attribute.comfort_grade_id,
        category.category_id,
        category.category AS category_name,
        category.friendly_url AS category_friendly_url,
        (SELECT price_now 
         FROM product_bedding_sizes AS size 
         WHERE size.product_id = product.product_id 
         ORDER BY size.price_now ASC 
         LIMIT 1) AS price
    FROM
     ...
) AS sub
WHERE price = ... <--- here it can see the price alias.

有关详细信息,请参阅此处:


或:您可以加入该表,而不是像这样的相关子查询:

SELECT
    product.product_id,
    product.range_id,
    product.title,
    product.image,
    product.image_text,
    product.friendly_url,
    attribute.comfort_grade_id,
    category.category_id,
    category.category AS category_name,
    category.friendly_url AS category_friendly_url,
    size.price_now 
FROM
    products AS product
LEFT JOIN
(
   SELECT product_id, MIN(price_now) AS price
   FROM product_bedding_sizes
   GROUP BY product_id
) AS size ON size.product_id = product.product_id
LEFT JOIN
    categories AS category ON product.category_id = category.category_id
LEFT JOIN
    product_bedding_attributes AS attribute ON product.product_id = attribute.product_id
$where price = ----;

答案 1 :(得分:0)

尝试使用变量:

@price:= (SELECT price_now 
          FROM product_bedding_sizes AS size 
          WHERE size.product_id = product.product_id 
          ORDER BY size.price_now ASC LIMIT 1) AS price;

然后将其引用为

WHERE @price > 9000;

答案 2 :(得分:0)

如果你有

 WHERE price > 0 AND price` <= 199`
在你的where子句中

然后尝试使用HAVING子句

像那样

 $HAVING
      //-- where $having  = HAVING price > 0 AND price <= 199