[英]An alternative to the WHERE IN clause for product filters
我正在寻找以下语句的替代SQL查询:
SELECT COUNT(`id`) FROM `products`
WHERE
`category` = "Motors" AND
`id` IN(SELECT `id` FROM `products` WHERE
`Horsepower` > 200 AND
`id` IN(SELECT `id` FROM `products` WHERE
`Manufacturer` = "Baldor"))
如您所见,理论上(因为我没有专门测试它),该子查询将查询所有选定的产品ID。 然后,从产品ID的最终列表中生成一个COUNT。 当有许多嵌套查询时,此方法会变慢。
我正在研究过滤系统。 因此,选择了一个或多个过滤器和子过滤器,并根据当前选择生成了一个COUNT。
如果我可以创建一个SQL语句以基于任意数量的子过滤器(不创建“ WHERE IN”子句)来返回产品数量,那将是很棒的选择。
可以简单地使上述查询仅使用WHERE ... AND子句。 问题在于将以下内容用作子查询,因为它需要选择多个条件:
SELECT `products`.`id` FROM `products`
LEFT JOIN `attributes` ON `attributes`.`product_id` = `products`.`id`
WHERE `attributes`.`Label` = "Horsepower" AND
`attributes`.`Value` > 200
SELECT `products`.`id` FROM `products`
LEFT JOIN `attributes` ON `attributes`.`product_id` = `products`.`id`
WHERE `attributes`.`Label` = "Category" AND
`attributes`.`Value` = "Motors"
为什么需要这个? 公正和要求在一起
select count(`id`) from `products` where category = "Motors" and `HorsePower` > 200 and `Manufacturer` = "Baldor"
假设您没有使用ORM(坦率地说,考虑到您要问的问题),通常在代码中执行此操作的技巧将是这样的
#Python
conds = ['category = "Motors"', '`Horsepower` > 200']
query = 'SELECT COUNT(`id`) FROM `products` WHERE ' + ' and '.join(conds)
如果需要从第二张表中拉出,可以执行以下操作:
select count(products.id) from products left join extra on extra.product_id = products.id where products.category = 'foo' and extra.fielda = 'blah' and extra.fieldb = 'bar'
如果需要多个表,则可以使用其他联接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.