我正在尝试在Wordpress中设置警报,以便用户可以创建警报,以便在创建的新帖子(属性)与其设置条件(警报)匹配时通知他们。我的计划是使用两个帖子类型,一个用于属性,一个用于警报。然后,当保存属性发布时,它将执行以下示例查询:
SELECT
post_author
FROM
wp_posts
INNER JOIN wp_postmeta m1
ON wp_posts.ID = m1.post_id
AND m1.meta_key = 'a_property_type'
AND m1.meta_value = 'flat'
INNER JOIN wp_postmeta m2
on wp_posts.ID = m2.post_id
AND m2.meta_key = 'a_bedrooms_min'
AND m2.meta_value <= '2'
INNER JOIN wp_postmeta m3
on wp_posts.ID = m3.post_id
AND m3.meta_key = 'a_bedrooms_max'
AND m3.meta_value >= '2'
INNER JOIN wp_postmeta m4
on wp_posts.ID = m4.post_id
AND m4.meta_key = 'a_bathrooms_min'
AND m4.meta_value <= '2'
INNER JOIN wp_postmeta m5
on wp_posts.ID = m5.post_id
AND m5.meta_key = 'a_bathrooms_max'
AND m5.meta_value >= '2'
INNER JOIN wp_postmeta m6
on wp_posts.ID = m6.post_id
AND m6.meta_key = 'a_garden'
AND m6.meta_value >= '1'
INNER JOIN wp_postmeta m7
on wp_posts.ID = m7.post_id
AND m7.meta_key = 'a_garage'
AND m7.meta_value >= '1'
INNER JOIN wp_postmeta m8
on wp_posts.ID = m8.post_id
AND m8.meta_key = 'a_parking'
AND m8.meta_value >= '1'
INNER JOIN wp_postmeta m9
on wp_posts.ID = m9.post_id
AND m9.meta_key = 'a_double_glazing'
AND m9.meta_value >= '1'
INNER JOIN wp_postmeta m10
on wp_posts.ID = m10.post_id
AND m10.meta_key = 'a_country'
AND m10.meta_value LIKE 'Scotland'
WHERE
wp_posts.post_type = 'alerts'
AND wp_posts.post_status = 'publish'
GROUP BY
wp_posts.ID
ORDER BY
wp_posts.post_date DESC
这可以并且确实返回与标准集匹配的属性,但是当我引入LIKE时,它确实使查询挂起。我正在使用默认的Wordpress表'wp_posts'和'wp_postmeta'。我已经尝试在列'meta_value'上设置一个索引,但因为它是一个'longtext'字段,它不允许我这样做。
有更好的解决方案可以做到这一点,还是可以更有效地编写查询?
由于
答案 0 :(得分:1)
除了eggyal提供的内容之外,我也会在(post_id,meta_key,meta_value)上添加索引。如果这对您的查询没有帮助,我会尝试另外一件事。将除LIKE之外的所有元素预先包装到预先查询中,以便首先处理内部查询并返回一小组ID,然后加入LIKE条件。
假设您有1000个属性,但只有35个属性符合您的所有其他条件,并在亚秒级时间内解决。现在,您只有35条记录将被解析为您的额外LIKE条件。像
这样的东西select
wp.Post_Author
from
( SELECT
post_id,
post_author
FROM
wp_posts
INNER JOIN wp_postmeta m1
ON wp_posts.ID = m1.post_id
AND m1.meta_key = 'a_property_type'
INNER JOIN the m2 through m9
WHERE
type and status criteria ) as PreQuery
INNER JOIN your m10 version
on PreQuery.Post_ID = m10.post_id
AND ... rest of join condition