我正在根据 $_GET[] 检索到的术语数量,使用 OR 条件的动态数量进行查询。
if(isset($_GET['terms']))
{
$concat_search = 'AND wp_posts.ID = wp_term_relationships.object_id';
$query_concat_strings .= 'AND (';
$no_commas = rtrim($_GET['terms'], ", tn");
$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)
这将返回与 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的工作方式存在一些误解。