In MySQL, you can do:
having rate > 5
MySQL has extended the having
clause so it can work without a group by
. Although questionable as a feature, it does allow you to reference aliases in the select
clause without using a subquery.
سؤال
I work with entity-attribute-value database model.
My product have many attribute_varchars and attribute_varchars have one attribute. An attribute has many attribute_varchars and an attribute varchar has one product. Same logic apply to attribute_decimals and attribute_texts.
Anyway, i have the following query and i would like to filter the result using a where clause
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
I would like to add a where rate > 5
I tried but I get the following error : Unknown column 'rate' in 'where clause'
. I tried adding an alias to the value and to the table of the value but nothing seems to work.
المحلول
In MySQL, you can do:
having rate > 5
MySQL has extended the having
clause so it can work without a group by
. Although questionable as a feature, it does allow you to reference aliases in the select
clause without using a subquery.
نصائح أخرى
With generated column like that, the best way is to made your query as a subquery, and do your filtering on the upper level like that:
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
Use join clauses rather than subqueries for the attribute tables:
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