减少内部联接

问题描述

| 我有以下SQL选择(SQLite / MySQL):
SELECT products.* FROM products
INNER JOIN specifications AS spec1 ON specifications.product_id = product.id
INNER JOIN specifications AS spec2 ON specifications.product_id = product.id

WHERE products.language = \"de\"
AND products.category = \"ABC\"


AND (spec1.name = \'Innenabmessungen\' AND spec1.value = \'182x53\')
AND (spec2.name = \'Farbe\'            AND spec2.value = \'schwarz\')
是否有一种解决方案,只使用一个
INNER JOIN
?问题是我想用两个以上的规格过滤器制作
SELECT
。这可能吗?     

解决方法

如果要从规格表中的两个记录中返回值,则不能简化它,因为在规格表中需要两次查找 但是,在您的示例中,您可以按以下方式重写它:
SELECT products.* FROM products

WHERE products.language = \"de\"
AND products.category = \"ABC\"
AND (SELECT COUNT(*) FROM specifications WHERE 
(specifications.name = \'Innenabmessungen\' AND specifications.value = \'182x53\' AND specifications.product_id = product.id) OR
(specifications.name = \'Farbe\' AND specifications.value = \'schwarz\' AND specifications.product_id = product.id)
) = 2
尽管我认为性能不会提高,除非您首先在规格表上查找以找到具有匹配product_id的行,然后查找名称/值 显然,您需要在规格表中索引product_id,名称和值字段,以及在products表中索引productid,语言和类别字段。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...