mysql 链接表 +加入+数数
我有一个想要优化的查询。我确信这个查询可以改进。
查询结果应返回 filter_id 为 22 和 2 且显示“yes”的产品数量。
SELECT COUNT(product_id) AS Total
FROM kkx_filters_products
LEFT JOIN kkx_products ON product_id = kkx_products.id
WHERE filter_id IN (2,22)
AND kkx_products.display = 'yes'
GROUP BY product_id
HAVING count(product_id) = 2
上述查询返回 10230 条记录,每条记录的字段为 Total,值为 2。
我想要一个包含字段 Total 和值 10230 的结果。
我已经包含了查询中使用的表的结构。
解释 kkx_filters;
Field Type Null Key Default Extra
id int(11) unsigned NO PRI NULL auto_increment
name varchar(50) NO
解释 kkx_filters_products;
Field Type Null Key Default Extra
filter_id int(11) NO PRI 0
product_id int(11) NO PRI 0
解释 kkx_products;
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
title varchar(255) NO
display enum('yes','no') NO yes
I've got a query that i'd like to optimize. I'm certain that this query can be improved.
The result of the query should return the number of products that have the filter_id 22 and 2 and have display 'yes'.
SELECT COUNT(product_id) AS Total
FROM kkx_filters_products
LEFT JOIN kkx_products ON product_id = kkx_products.id
WHERE filter_id IN (2,22)
AND kkx_products.display = 'yes'
GROUP BY product_id
HAVING count(product_id) = 2
The above query returns 10230 records each with the field Total and value 2.
I'd like one result with the field Total and value 10230.
I've included the structure of the tables being used in the query.
EXPLAIN kkx_filters;
Field Type Null Key Default Extra
id int(11) unsigned NO PRI NULL auto_increment
name varchar(50) NO
EXPLAIN kkx_filters_products;
Field Type Null Key Default Extra
filter_id int(11) NO PRI 0
product_id int(11) NO PRI 0
EXPLAIN kkx_products;
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
title varchar(255) NO
display enum('yes','no') NO yes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以用:包装您的查询
,但效率不会很高。相反,将产品表连接到过滤器表两次:
You could wrap your query with:
but it won't be very efficient. Instead, join the products table to the filter table, twice: