我使用实体-属性-值数据库模型。
我的产品有很多 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
我想添加一个 where rate > 5
我试过了,但出现以下错误:“where 子句”中的未知列“rate”
。我尝试向值和值表添加别名,但似乎没有任何效果。
最佳答案
在 MySQL 中,您可以:
having rate > 5
MySQL 扩展了 having
子句,因此它可以在没有 group by
的情况下工作。虽然作为一项功能值得怀疑,但它确实允许您在 select
子句中引用别名,而无需使用子查询。
关于MySQL where 子句定位依赖子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793306/