MySQL where子句定位依赖子查询

时间:2013-11-05 16:02:08

标签: mysql sql entity-attribute-value

我使用entity-attribute-value数据库模型。

我的产品有很多attribute_varchars,attribute_varchars有一个属性。属性具有许多attribute_varchars,属性varchar具有一个产品。相同的逻辑适用于attribute_decimals和attribute_texts。

无论如何,我有以下查询,我想使用where子句

过滤结果
SELECT 
    products.id,
    (select value from attribute_texts    where product_id = products.id and attribute_id = 1) 
        as description,
    (select value from attribute_varchars where product_id = products.id and attribute_id = 2) 
        as model,
    (select value from attribute_decimals where product_id = products.id and attribute_id = 9) 
        as rate,
    (select value from attribute_varchars where product_id = products.id and attribute_id = 20) 
        as batch
FROM products
WHERE products.status_id <> 5

我想添加一个rate > 5

我试过,但收到以下错误:Unknown column 'rate' in 'where clause'。我尝试在值和表的值中添加别名,但似乎没有任何效果。

3 个答案:

答案 0 :(得分:2)

在MySQL中,你可以这样做:

having rate > 5

MySQL扩展了having子句,因此它可以在没有group by的情况下工作。虽然作为一个功能有问题,但它确实允许您在select子句中引用别名而不使用子查询。

答案 1 :(得分:1)

使用这样生成的列,最好的方法是将查询作为子查询,并在上层进行过滤:

SELECT *
FROM
(
SELECT 
    products.id,
    (select value from attribute_texts    where product_id = products.id and attribute_id = 1) 
        as description,
    (select value from attribute_varchars where product_id = products.id and attribute_id = 2) 
        as model,
    (select value from attribute_decimals where product_id = products.id and attribute_id = 9) 
        as rate,
    (select value from attribute_varchars where product_id = products.id and attribute_id = 20) 
        as batch

FROM products
WHERE products.status_id <> 5
) as sub
WHERE sub.Rate > 5

答案 2 :(得分:0)

对属性表使用join子句而不是子查询:

SELECT 
    p.id,
    a_description.value AS description,
    a_model.value       AS model,
    a_rate.value        AS rate,
    a_batch.value       AS batch
FROM products p
INNER JOIN attribute_texts a_description 
    ON  a_description.product_id = p.id
    AND a_description.attribute_id = 1
INNER JOIN attribute_varchars a_model 
    ON  a_model.product_id = p.id
    AND a_model.attribute_id = 2
INNER JOIN attribute_decimals a_rate 
    ON  a_rate.product_id = p.id
    AND a_rate.attribute_id = 9
INNER JOIN attribute_varchars a_batch
    ON  a_batch.product_id = p.id
    AND a_batch.attribute_id = 20
WHERE products.status_id <> 5
  AND a_rate.value > 5