0

我有一个 MySQL 语句,它执行内部SELECT并将结果作为伪列返回。我想在我的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'

我怎样才能解决这个问题并实际使用price我的WHERE子句中的值?

4

3 回答 3

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 = ----;
于 2013-02-15T16:31:24.913 回答
0

如果你有

 WHERE price > 0 AND price` <= 199`

在你的 where 子句中

然后尝试使用 HAVING 子句执行此操作

像那样

 $HAVING
      //-- where $having  = HAVING price > 0 AND price <= 199
于 2013-02-16T12:19:38.730 回答
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;
于 2013-02-15T18:39:40.020 回答