是否有必要使用多个左连接和内连接来优化此查询?

时间:2016-01-23 03:53:35

标签: mysql sql join mariadb

我正在使用Mariadb 10.我已经构建了一个查询来获取模型的变体。这很直截了当 这是一个例子(在我的实际案例中提取更多列):

$sql = "
SELECT v.name,v.color,v.material,
       m.modelID,m.model_overview,
       b.brand,b.brand_overview,
       s.seller,s.sell_id,s.price,
       rm.similar_model,rm.similar_model_overview,
       r.review,r.rating
FROM variant v 
  INNER JOIN model m ON v.modelID = m.modelID
  INNER JOIN brand b ON b.brandID = m.brandID
  LEFT JOIN seller s ON s.sellerID = v.sellerID 
  LEFT JOIN related_model rm ON rm.modelID = m.modelID
  LEFT JOIN review r ON r.modelID = m.modelID
  // more left joins to other tables ON m.modelID in real case 
WHERE v.ID = :id";

$dbh->prepare($sql);

我依稀记得在一篇文章中,为了避免因多个左连接而创建大量行,最好将内连接查询分组到子查询中,然后使用返回的modelID左连接其他表,如下所示:

$sql = "
SELECT all.*,s.seller,s.sell_id,s.price,
       rm.similar_model,rm.similar_model_overview,
       r.review,r.rating
FROM (
  SELECT v.name,v.color,v.material,
       m.modelID,m.model_overview,
       b.brand,b.brand_overview,
       v.sellerID
  FROM variant v 
       INNER JOIN model m ON v.modelID = m.modelID
       INNER JOIN brand b ON b.brandID = m.brandID
       WHERE v.ID = :id
)all 
LEFT JOIN seller s ON s.sellerID = all.sellerID 
LEFT JOIN related_model rm ON rm.modelID = all.modelID
LEFT JOIN review r ON r.modelID = all.modelID";    

这是真的吗?这个查询在性能方面比原始查询更好吗?

0 个答案:

没有答案