如果我处在你的处境,我会用不同的方法。
只需在更新goals\\u Make时自动添加隐藏的元字段即可。
E、 g。
add_action(\'updated_postmeta\', \'update_goal_made\', 20, 4);
function update_goal_made( $meta_id, $object_id, $meta_key, $_meta_value ) {
if ( $meta_key != \'goals-made\') return; // run only when update meta \'goals-made\'
// get the goals-against for post
$against = get_post_meta($object_id, \'goals-against\', true) ? : 1;
// if \'goals-made\' > \'goals-against\' create/update a field \'_goals-won\' setted to 1
if ( intval($_meta_value) > intval($against) ) {
update_post_meta($object_id, \'_goals-won\', \'1\');
} else {
// if not delete \'_goals-won\' post meta (if exists)
delete_post_meta($object_id, \'_goals-won\');
}
}
现在检索帖子
_goals-won
存在,只需运行元查询:
$args = (
\'posts_per_page\' => -1,
\'meta_query\' => array( array(\'meta_key\'=>\'_goals-won\') )
);
$won_posts = get_posts($args);
在上完成一些工作后编辑
GhostToast answer 我还可以为您提供正确的SQL查询,以获得相同的结果。
global $wpdb;
$won_posts = $wpdb->get_results( "
SELECT $wpdb->posts.*
FROM $wpdb->posts
INNER JOIN $wpdb->postmeta AS mt1 ON ( $wpdb->posts.ID = mt1.post_id )
INNER JOIN $wpdb->postmeta AS mt2 ON ( $wpdb->posts.ID = mt2.post_id )
WHERE mt1.meta_key = \'goals-made\'
AND (
mt2.meta_key = \'goals-against\'
AND CAST( mt1.meta_value AS UNSIGNED ) > CAST( mt2.meta_value AS UNSIGNED )
)
GROUP BY $wpdb->posts.ID
" );
<小时>
Side note:
如果有人编写SQL语句来处理您的请求,请确保SQL语句的性能低于最简单的元查询(如第一次发布的查询)。