在工作中,我遇到了这种查询:

select distinct psv.pack_id from pack_store_variant psv, pack p
where p.id = psv.pack_id and p.store_id = 1 and psv.store_variant_id = 196;


作为select from table1, table2的新手,我做了一些搜索,发现这基本上是两个表的笛卡尔积。我认为这不必要地创建了NxM行,我们可以只使用常规联接,它应该可以工作。所以我写了这个查询:

SELECT DISTINCT pack_id from (SELECT pack_id, store_id, store_variant_id
FROM pack JOIN pack_store_variant ON pack.id = pack_store_variant.pack_id) as comb
where comb.store_id = 1 AND comb.store_variant_id = 196;


令人惊讶的是,当我进行比较时,第一个比我的快一个数量级。我的查询会以某种方式吸吮吗?还是我不正确理解交叉联接/内部联接之间的区别?

最佳答案

您的查询不是很好。您将查询分为两个选择。内部的将创建一个表,然后在该表上再次选择。那不是很有效。这就是我要做的。

select distinct psv.pack_id from pack_store_variant as  psv
Join pack as p on p.id = psv.pack_id
where p.store_id = 1 and psv.store_variant_id = 196;

关于mysql - 交叉联接比内部联接快得多,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38430726/

10-12 22:34