减少内部联接

时间:2011-05-26 09:00:31

标签: sql select inner-join

我有以下SQL-Select(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的解决方案?问题是我想使用两个以上的spec-filter制作SELECT s。这可能吗?

1 个答案:

答案 0 :(得分:1)

如果要从规范表中的两个记录返回值,则无法简化,因为规范表上需要两次查找

但是在您的示例中,您可以按如下方式重写它:

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,name和value字段,以及products表中的productid,language和category字段。