1

这是查询需要 12 秒的时间

SELECT SQL_CALC_FOUND_ROWS DISTINCT `t`.* FROM `wp_pods_bars` AS `t` 
LEFT JOIN `wp_podsrel` AS `rel_city` ON 
    ( `rel_city`.`field_id` = 13918 AND `rel_city`.`item_id` = `t`.`id` ) OR 
    ( `rel_city`.`related_field_id` = 13918 AND `rel_city`.`related_item_id` = `t`.`id` ) 

如果我做

SELECT SQL_CALC_FOUND_ROWS DISTINCT `t`.* FROM `wp_pods_bars` AS `t` 
LEFT JOIN `wp_podsrel` AS `rel_city` ON 
    ( `rel_city`.`field_id` = 13918 AND `rel_city`.`item_id` = `t`.`id` )

或者

SELECT SQL_CALC_FOUND_ROWS DISTINCT `t`.* FROM `wp_pods_bars` AS `t` 
LEFT JOIN `wp_podsrel` AS `rel_city` ON 
    ( `rel_city`.`related_field_id` = 13918 AND `rel_city`.`related_item_id` = `t`.`id` ) 

每个查询运行 0.09 秒。为什么会这样以及如何解决这个问题?

编辑:

EXPLAIN SELECT SQL_CALC_FOUND_ROWS DISTINCT `t`.* FROM `wp_pods_bars` AS `t` 
LEFT JOIN `wp_podsrel` AS `rel_city` ON 
    ( `rel_city`.`related_field_id` = 13918 AND `rel_city`.`related_item_id` = `t`.`id` ) 

结果

id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,SIMPLE,t,ALL,NULL,NULL,NULL,NULL,1340,Using temporary
1,SIMPLE,rel_city,ref,rel_field_rel_item_idx,rel_field_item_idx,rel_field_rel_item_idx,14,const,barchick.t.id,1,Using index; Distinct

第二

EXPLAIN SELECT SQL_CALC_FOUND_ROWS DISTINCT `t`.* FROM `wp_pods_bars` AS `t` 
LEFT JOIN `wp_podsrel` AS `rel_city` ON 
( `rel_city`.`related_field_id` = 13918 AND `rel_city`.`related_item_id` = `t`.`id` ) 

结果

id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,SIMPLE,t,ALL,NULL,NULL,NULL,NULL,1340,Using temporary
1,SIMPLE,rel_city,ref,rel_field_rel_item_idx,rel_field_item_idx,rel_field_rel_item_idx,14,const,barchick.t.id,1,Using index; Distinct 
4

1 回答 1

1

您拥有的LEFT联接是多余的,因为您没有对结果中的任何内容使用正确的表。连接产生的任何重复行都被DISTINCT.

因此,您的查询等效于从表中获取所有行的查询(只要 中存在主键或唯一键wp_pods_bars):

SELECT t.* FROM wp_pods_bars AS t ;

DISTINCT,不JOIN,不OR


MariaDB 中有一个名为Table Elimination的功能(另请参阅Sergey Petrunia 的博客中的解释),它可以按照您的意愿工作并消除连接,但当然从 MySQL 切换到 MariaDB 可能对您来说不是一个可用的选项。

于 2013-06-28T06:51:50.920 回答