0

我使用实体-属性-值数据库模型。

我的产品有很多 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'。我尝试为值和值表添加别名,但似乎没有任何效果。

4

3 回答 3

2

在 MySQL 中,您可以执行以下操作:

having rate > 5

MySQL 扩展了该having子句,因此它可以在没有group by. 尽管作为一项功能值得怀疑,但它确实允许您在select不使用子查询的情况下引用子句中的别名。

于 2013-11-05T16:05:01.853 回答
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
于 2013-11-05T16:04:53.157 回答
0

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

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
于 2013-11-05T16:09:17.543 回答