有人可以帮助我理解为什么第二个查询这么快吗?
这来自WordPress数据库,其中wp_posts是具有列ID, post_title, post_status...
的表,而wp_postmeta是具有列ID, post_id, meta_key, meta_value
的表。 wp_posts.ID对应于wp_postmeta.post_id。
我已经查看了Explain的输出,但是我不清楚。我看到查询以略有不同的顺序执行,但我不真正理解为什么更改顺序或为什么速度如此之快。
我真的很想了解,所以我知道它是否适用于其他查询。
谢谢!
SELECT
COALESCE( SUM( wpm1.meta_value ), 0 ) as package_sum,
wpm2.meta_value as prp_id
FROM wp_posts
LEFT JOIN wp_postmeta wpm1 ON wpm1.post_id = wp_posts.ID
LEFT JOIN wp_postmeta wpm2 ON wpm2.post_id = wp_posts.ID
LEFT JOIN wp_postmeta wpm3 ON wpm3.post_id = wp_posts.ID
WHERE post_type='voucher'
AND post_status IN ( 'requested', 'disputed', 'issued', 'visit-required', 'claimed', 'witheld', 'approved', 'paid' )
AND wpm1.meta_key='voucher_value'
AND wpm2.meta_key='prp'
AND wpm3.meta_key='supplier'
AND wpm3.meta_value='955'
GROUP BY wpm2.meta_value
EXPLAIN:
-----------------------
id select_type table type possible_keys key key_len ref rows filtered Extra
1 SIMPLE wpm2 ref post_id,meta_key meta_key 767 const 80212 100.00 Using where; Using temporary; Using filesort
1 SIMPLE wp_posts eq_ref PRIMARY,type_status_date PRIMARY 8 gigabit.wpm2.post_id 1 100.00 Using where
1 SIMPLE wpm3 ref post_id,meta_key post_id 8 gigabit.wpm2.post_id 50 100.00 Using where
1 SIMPLE wpm1 ref post_id,meta_key post_id 8 gigabit.wpm2.post_id 50 100.00 Using where
SELECT
COALESCE( SUM( wpm1.meta_value ), 0 ) as package_sum,
wpm2.meta_value as prp_id
FROM wp_posts
LEFT JOIN wp_postmeta wpm1 ON wpm1.post_id = wp_posts.ID AND wpm1.meta_key='voucher_value'
LEFT JOIN wp_postmeta wpm2 ON wpm2.post_id = wp_posts.ID AND wpm2.meta_key='prp'
LEFT JOIN wp_postmeta wpm3 ON wpm3.post_id = wp_posts.ID AND wpm3.meta_key='supplier'
WHERE post_type='voucher'
AND post_status IN ( 'requested', 'disputed', 'issued', 'visit-required', 'claimed', 'witheld', 'approved', 'paid' )
AND wpm3.meta_value='955'
GROUP BY wpm2.meta_value
EXPLAIN:
-----------------------
id select_type table type possible_keys key key_len ref rows filtered Extra
1 SIMPLE wpm3 ref post_id,meta_key meta_key 767 const 71970 100.00 Using where; Using temporary; Using filesort
1 SIMPLE wp_posts eq_ref PRIMARY,type_status_date PRIMARY 8 gigabit.wpm3.post_id 1 100.00 Using where
1 SIMPLE wpm1 ref post_id,meta_key post_id 8 gigabit.wpm3.post_id 50 100.00 Using where
1 SIMPLE wpm2 ref post_id,meta_key post_id 8 gigabit.wpm3.post_id 50 100.00 Using where