Mysql OR 条件并按相关性排序

Mysql OR conditions and sort by relevance

我正在使用动态数量的 OR 条件进行查询,具体取决于 $_GET[] 检索到的术语数量。

    if(isset($_GET['terms']))
    {
        $concat_search = 'AND wp_posts.ID = wp_term_relationships.object_id';

        $query_concat_strings .= 'AND (';

        $no_commas = rtrim($_GET['terms'], ", \t\n");

        $terms = explode(',', $no_commas);

        $total_terms = count($terms);

        for($x = 0; $x < $total_terms; $x++)
        {
            $term_id = term_exists($terms[$x], 'especialidad');

            if ($term_id !== 0 && $term_id !== null)
            {           
                if($x == 0)
                {
                    $query_concat_strings .= ' wp_term_relationships.term_taxonomy_id ='.$term_id[term_id];
                }
                else
                {
                    $query_concat_strings .= ' OR wp_term_relationships.term_taxonomy_id ='.$term_id[term_id];
                }
            }
        }
        $query_concat_strings .= ')';
    }

    $querystr = "
        SELECT $wpdb->posts.* 
        FROM $wpdb->posts, $wpdb->postmeta, $wpdb->term_relationships
        WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
        ".$concat_search."
        AND $wpdb->postmeta.meta_key = 'wpcf-fin-oferta'
        AND $wpdb->postmeta.meta_value > $currentdate
        AND $wpdb->posts.post_status = 'publish' 
        AND $wpdb->posts.post_type = 'oferta'".$query_concat_strings."
        ORDER BY $wpdb->posts.ID 
        LIMIT $start, $posts_per_page
        ";

//The query echoed: SELECT wp_posts.* FROM wp_posts, wp_postmeta, wp_term_relationships WHERE wp_posts.ID = wp_postmeta.post_id AND wp_posts.ID = wp_term_relationships.object_id AND wp_postmeta.meta_key = 'wpcf-fin-oferta' AND wp_postmeta.meta_value > 1456700400 AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'oferta' AND ( wp_term_relationships.term_taxonomy_id =50 OR wp_term_relationships.term_taxonomy_id =7)

这将 return 所有匹配 wp_term_relationships.term_taxonomy_id =50 或 wp_term_relationships.term_taxonomy_id =7 的值,但我想对结果进行排序,优先考虑那些不仅匹配一个而且匹配多个的值条件,第一个 匹配的条件比其他条件多。

试过这个:

SELECT wp_posts.*, SUM(IF(wp_term_relationships.term_taxonomy_id ='11',1,NULL)) AS cond_matched, SUM(IF(wp_term_relationships.term_taxonomy_id ='50',1,NULL)) AS  cond_matched, SUM(IF(wp_term_relationships.term_taxonomy_id ='7',1,NULL)) AS cond_matched FROM wp_posts, wp_postmeta, wp_term_relationships WHERE wp_posts.ID = wp_postmeta.post_id AND wp_posts.ID = wp_term_relationships.object_id AND wp_postmeta.meta_key = 'wpcf-fin-oferta' AND wp_postmeta.meta_value > 1456786800 AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'oferta' GROUP BY wp_posts.ID ORDER BY cond_matched;

但结果似乎完全随机排列。 预期结果应该是: 如果我搜索 1、2、3

结果 1:包含所有 3 个值的结果:1,2,3,4,5,6,7 结果 2:那些至少有 2 个:1,3,7,9 结果3:只有1的那些:3,11,90,12

我唯一需要的是添加:

ORDER BY COUNT(*) DESC

查询结束。显然,就我而言,对 Mysql 的工作方式存在一些误解。