简体   繁体   English

MySQL使用几个WHERE子句选择AVG

[英]MySQL Select AVG using several WHERE clauses

I have a search engine for an online shop, i want to give the user the chance to filter the products by rating, until now my query looks like this: 我有一个在线商店的搜索引擎,我想给用户提供按评分过滤产品的机会,直到现在我的查询看起来像这样:

SELECT products.*,prices.price,AVG(ratings_products.rating)
FROM products,prices,ratings_products
WHERE products.title REGEXP 'lg' AND products.active = 'yes'
AND prices.price >= '10' AND prices.price <= '298650'
AND products.cod_product = prices.id_product
AND ratings_products.ratings >= '40' AND ratings_products.ratings <= 59
AND ratings_products.id_product = products.cod_product
AND products.id_category = '59' LIMIT 0,1

The idea is to filter by price, specific filters and rating, all works except the ratings. 想法是按价格,特定的过滤器和等级进行过滤,除等级以外的所有作品均如此。 I have the table ratings_products with the following structure: 我有具有以下结构的表ratings_products:

id | id_product | id_user | title | comment | date | rating
1  |      18    |    65   |awesome| some    |12344 | 85
2  |      18    |    84   |cool   | great   |12345 | 20

Now i need to AVG to return the average between 85 and 20, but the query is returning NULL, if i delete the ratings_products.rating <= 59 it gives me the result but is not calculating the average. 现在,我需要AVG返回85至20之间的平均值,但查询返回的是NULL,如果我删除ratings_products.rating <= 59它会给我结果,但不计算平均值。

Appreciate any help 感谢任何帮助

Thanks 谢谢

AND ratings_products.ratings >= '40' AND ratings_products.ratings <= 59

This means you want the values between 40 and 59. You display 20 and 85 in your example, neither is in the range you query for so that result is NULL 这意味着您需要介于40和59之间的值。在您的示例中显示20和85,两者都不在您查询的范围内,因此结果为NULL

Removing the AND ratings_products.ratings <= 59 part leaves a query for ratings higher than 40, that is 85, on its own, nothing to average. 删除AND ratings_products.ratings <= 59部分,将查询大于40的评分,即85本身没有平均值。

Am I missing something or are you querying for the wrong values? 我是否缺少某些内容?还是您要查询错误的值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM