Meta_Query比较运算符说明

时间:2012-10-29 作者:dev-jim

我注意到在meta\\u查询中有很多操作符可以用于比较。然而,我不太确定我应该使用什么操作符,这有点让人困惑=LIKE 操作人员

我想知道每个操作符的确切含义,以及我应该在什么条件下使用它们。

=
!=
>
>=
<
<=
LIKE
NOT LIKE
IN
NOT IN
BETWEEN
NOT BETWEEN
NOT EXISTS
谢谢。

2 个回复
最合适的回答,由SO网友:Jen 整理而成

The first several work as you would expect:

=   equals
!=  does not equal
>   greater than
>=  greater than or equal to
<   less than
<=  less than or equal to



LIKE and NOT LIKE

LIKE and NOT LIKE are SQL operators that let you add in wild-card symbols, so you could have a meta query that looks like this:

array( 
    \'key\' => \'name\', 
    \'value\' => \'Pat\', 
    \'compare\' => \'LIKE\'
)

This would return all posts where the meta value "name" has the string "Pat". In this case, "Pat" "Patricia" and "Patrick" would all be returned back to you. There\'s a non-WordPress tutorial explanation here.

Adding the wildcard character % isn\'t necessary, because it gets added by default like @Herb said in his below answer. Like this: $meta_value = \'%\' . like_escape( $meta_value ) . \'%\'; - see source.



IN and NOT IN

IN and NOT IN select any matches that are in (or not in) the given array. So you could do something like this:

array(
    \'key\'     => \'color\', 
    \'value\'   => array(\'red\', \'green\', \'blue\') 
    \'compare\' => \'IN\'
)

and it would get all posts that have the color set to either red, green, or blue. Using \'NOT IN\' gets the reverse, any posts that have a value set to anything else than what\'s in the array.

The generated SQL for this would look something like this:

SELECT * FROM posts_meta WHERE value IN ("red", "green", "blue") 



BETWEEN and NOT BETWEEN

BETWEEN and NOT BETWEEN allow you to define a range of values that could be correct, and require you to give two values in an array in your meta_query:

array( 
    \'key\' => \'price\', 
    \'value\' => array(20,30) 
    \'compare\' => \'BETWEEN\'
)

This will get you all posts where the price is between 20 and 30. This person digs into an example with dates.



NOT EXISTS

NOT EXISTS is just like what it sounds - the meta value isn\'t set or is set to a null value. All you need for that query is the key and comparison operator:

array( 
    \'key\' => \'price\', 
    \'compare\' => \'NOT EXISTS\'
)

This person needed to query non-existent meta values, and needed them to play nice with others.

Hope this helps!

SO网友:bobbingwide

请注意,当使用meta\\u compare值“LIKE”时,WordPress会自动将通配符(%)包装在meta\\u值字符串周围。因此,“Pat%”示例可能无法返回任何结果。

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post