删除'重复'来自全文查询

时间:2017-11-30 11:39:28

标签: mysql sql wordpress

我正在使用全文展开默认的WordPress搜索,并且有一个看起来像这样的SQL查询

SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.*,
  MATCH (wp_posts.post_title, wp_posts.post_content) AGAINST ('"string" @4' IN BOOLEAN MODE) AS p_score,
  MATCH (wp_postmeta.meta_value) AGAINST ('"string" @4' IN BOOLEAN MODE) AS pm_score
FROM wp_posts
  LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
  LEFT JOIN wp_icl_translations ON wp_posts.ID = wp_icl_translations.element_id
  LEFT JOIN wp_icl_languages ON wp_icl_translations.language_code = wp_icl_languages.code AND wp_icl_languages.active = 1
WHERE 1=1
  AND IF(
    MATCH (wp_posts.post_title, wp_posts.post_content) AGAINST ('"string" @4' IN BOOLEAN MODE) > MATCH (wp_postmeta.meta_value) AGAINST ('"string" @4' IN BOOLEAN MODE),
    MATCH (wp_posts.post_title, wp_posts.post_content) AGAINST ('"string" @4' IN BOOLEAN MODE) > 0,
    MATCH (wp_postmeta.meta_value) AGAINST ('"string" @4' IN BOOLEAN MODE) > 0
  )
  AND wp_icl_translations.language_code = 'hr'
  AND wp_posts.post_status = 'publish'
ORDER BY p_score DESC LIMIT 0, 12

问题是我在结果表中同时包含p_scorepm_score,因此会出现重复项

ID  | ... | p_score  | pm_score
234 | ... | 9.234234 | 8.234323
234 | ... | 9.234234 | 0

虽然从技术上讲它们并不重复(不同分数),但我仍然在搜索中看到重复。

可以进行查询,以便在获得MATCH的结果后,我会比较哪个得分(p_scorepm_score)更高,然后只选择带有更高的分数显示?我在WHERE条款中尝试了类似的东西,但很明显,我做错了。

1 个答案:

答案 0 :(得分:1)

您应该能够使用GREATEST() MySQL函数。

SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.*,
  GREATEST(
    MATCH (wp_posts.post_title, wp_posts.post_content) AGAINST ('"string" @4' IN BOOLEAN MODE),
    MATCH (wp_postmeta.meta_value) AGAINST ('"string" @4' IN BOOLEAN MODE)
  ) as score
FROM wp_posts
  LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
  LEFT JOIN wp_icl_translations ON wp_posts.ID = wp_icl_translations.element_id
  LEFT JOIN wp_icl_languages ON wp_icl_translations.language_code = wp_icl_languages.code AND wp_icl_languages.active = 1
WHERE 1=1
  AND IF(
    MATCH (wp_posts.post_title, wp_posts.post_content) AGAINST ('"string" @4' IN BOOLEAN MODE) > MATCH (wp_postmeta.meta_value) AGAINST ('"string" @4' IN BOOLEAN MODE),
    MATCH (wp_posts.post_title, wp_posts.post_content) AGAINST ('"string" @4' IN BOOLEAN MODE) > 0,
    MATCH (wp_postmeta.meta_value) AGAINST ('"string" @4' IN BOOLEAN MODE) > 0
  )
  AND wp_icl_translations.language_code = 'hr'
  AND wp_posts.post_status = 'publish'
ORDER BY p_score DESC LIMIT 0, 12

这应该让你选择最好的两个,并将它们作为score

如果您想知道它是p_score还是pm_score,那么您可能需要继续获得两个分数并在代码级别处理重复和比较。