在工作中我遇到了这样的查询:
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/