如何更快地使这些wp_postmeta MySQL查询?

时间:2016-08-04 01:29:07

标签: mysql

我正在制作一个搜索功能,当在每个下拉菜单中进行选择时,该功能会更新可用选项。

以下是两个运行以更新两个下拉菜单的mysql查询。在db中有大约5000个产品,每个查询大约需要4秒。我怎样才能加速它们?

我尝试将它们组合成单个查询并使用PHP进行分组,但如果选项被清除,则所选下拉列表中的选项将不可用。

SELECT DISTINCT l.meta_value AS ship_id
FROM wp_posts a
JOIN wp_postmeta f ON ID = f.post_id
JOIN wp_postmeta g ON ID = g.post_id
JOIN wp_postmeta h ON ID = h.post_id
JOIN wp_postmeta d ON ID = d.post_id JOIN wp_postmeta i ON ID = i.post_id 
JOIN wp_postmeta l ON ID = l.post_id
WHERE post_type = 'product'
AND f.meta_key = 'first_start_date'
AND g.meta_key = 'last_start_date'
AND h.meta_key = 'product_group'
AND h.meta_value = 'cruises'
AND d.meta_key = 'destinationregion'
AND i.meta_key = 'destinationarea'
AND 'South America' IN (d.meta_value, i.meta_value)
AND (
        (CONCAT('2016', '01-01') BETWEEN STR_TO_DATE(f.meta_value, '%b %e, %Y') AND STR_TO_DATE(g.meta_value, '%b %e, %Y')) OR
        (STR_TO_DATE(f.meta_value, '%b %e, %Y') BETWEEN CONCAT('2016', '-01-01') AND CONCAT('2016' + 1, '-01-01'))
    )
AND l.meta_key = 'cruiseship'
ORDER BY l.meta_value ASC

-

SELECT DISTINCT d.meta_value AS destinationregion, i.meta_value AS destinationarea
FROM wp_posts a
JOIN wp_postmeta f ON ID = f.post_id
JOIN wp_postmeta g ON ID = g.post_id
JOIN wp_postmeta h ON ID = h.post_id
JOIN wp_postmeta d ON ID = d.post_id JOIN wp_postmeta i ON ID = i.post_id
WHERE post_type = 'product'
AND f.meta_key = 'first_start_date'
AND g.meta_key = 'last_start_date'
AND h.meta_key = 'product_group'
AND h.meta_value = 'cruises'
AND (
        (CONCAT('2016', '01-01') BETWEEN STR_TO_DATE(f.meta_value, '%b %e, %Y') AND STR_TO_DATE(g.meta_value, '%b %e, %Y')) OR
        (STR_TO_DATE(f.meta_value, '%b %e, %Y') BETWEEN CONCAT('2016', '-01-01') AND CONCAT('2016' + 1, '-01-01'))
    )
AND d.meta_key = 'destinationregion' AND i.meta_key = 'destinationarea'
ORDER BY destinationregion, destinationarea"

2 个答案:

答案 0 :(得分:0)

您可以尝试查询的聚合形式:

这个想法是:

select p.id,
       max(case when pm.meta_key = 'First_start_date' then pm.meta_value end) as first_start_date,
       max(case when pm.meta_key = 'last_start_date' then pm.meta_value end) as last_start_date,       
       max(case when pm.meta_key = 'product_group' then pm.meta_value end) as product_group,
       max(case when pm.meta_key = 'destinationregion' then pm.meta_value end) as destinationregion,
       max(case when pm.meta_key = 'destinationarea' then pm.meta_value end) as destinationarea,
       max(case when pm.meta_key = 'cruiseship' then pm.meta_value end) as cruiseship
from wp_posts p join
     wp_postmeta pm
     on pm.post_id = p.id
where p.post_type = 'product'
group by p.id ;

您可以使用having子句或子查询来获取值的特定过滤条件。

wp_posts(product, id)上的索引可能有助于查询。

答案 1 :(得分:0)

修改您的数据模型,以便以下工作无需其他功能:

WHERE f.meta_value < '2017-01-01' AND g.meta_value > '2016-01-01'

我无法记住您是否可以自定义wp,以便可以根据数据类型在表中排列值,但如果没有,则至少将日期存储为格式正确的字符串。

我认为(post_id,meta_key,meta_value)上有一个复合索引