简单的内部联接和索引

时间:2019-02-14 13:49:27

标签: mysql query-optimization

我有一个简单的内部联接查询,如下所示:

SELECT DISTINCT t.guid, t.post_title 
FROM wph3_posts t 
INNER JOIN wph3_postmeta tr 
ON t.ID = tr.post_id AND tr.meta_value LIKE '%>Washing</a>%' AND t.post_status = 'Publish' 
ORDER BY t.post_date DESC LIMIT 3

当我做一个MySQL解释时,我得到以下输出:

|id|select type|table|type|possible_key|key|key_len|ref|rows|extra|
:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|
|1|SIMPLE|t|ALL|PRIMARY, myKey|NULL|NULL|NULL|29859|Using where; Using temporary; Using filesort|
|1|SIMPLE|tr|ref|post_id|post_id|8|y345435_wp946.t.ID|6|Using where; Distinct|

“ myKey”索引刚刚创建,并且是具有 wph3_posts(ID为post_status)的索引

尽管该键仍然被忽略,并且对于所使用的键显示为NULL。 该查询大约需要 1.4230 来执行,而我真的想缩小范围。

编辑:交换我的主要订单: wph3_posts与(post_status,ID)后,我可以将 myKey 用作索引,但是不幸的是,它没有做很多事情。

1 个答案:

答案 0 :(得分:0)

非常感谢Barmar向我指出这一点。

在原始查询中,我正在搜索所有元值,而不是告诉它搜索要查找的特定键下的元值。 因此, tr.meta_key = 'item_html' AND tr.meta_value LIKE '%>Washing</a>%' 是关键。

我更新的查询:

SELECT DISTINCT t.guid, t.post_title 
FROM wph3_posts t 
INNER JOIN wph3_postmeta tr 
ON t.ID = tr.post_id AND tr.meta_key = 'item_html' AND tr.meta_value LIKE '%>Washing</a>%' AND t.post_status = 'Publish' 
ORDER BY t.post_date DESC LIMIT 3

这将查询时间减少到0.2171秒,这是对查询时间的很好的改进。