MySQL LIKE运算符的行为类似于=运算符

时间:2014-10-09 10:48:00

标签: mysql sql-like wpdb

似乎MySQL的LIKE运算符的行为类似于a =运算符。

以下MySQL查询返回预期结果(1个条目):

$meta_key = '_locality';
$meta_value = 'The Hague';
$post_ids = $wpdb->get_col( $wpdb->prepare( 
  "
  SELECT      post_id
  FROM        $wpdb->postmeta
  WHERE       meta_key = %s
              AND meta_value LIKE %s
  ", 
  $meta_key, 
  $meta_value
) );

但是,以下仅包含原始meta_value的一部分,返回一个空数组:

$meta_key = '_locality';
$meta_value = 'The';
$post_ids = $wpdb->get_col( $wpdb->prepare( 
  "
  SELECT      post_id
  FROM        $wpdb->postmeta
  WHERE       meta_key = %s
              AND meta_value LIKE %s
  ", 
  $meta_key, 
  $meta_value
) );

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

请仔细阅读mysql模式匹配语法:http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html。 LIKE匹配会丢失'%':

$meta_key = '_locality';
$meta_value = '%The Hague%';
$post_ids = $wpdb->get_col( $wpdb->prepare( 
  "
  SELECT      post_id
  FROM        $wpdb->postmeta
  WHERE       meta_key = %s
              AND meta_value LIKE %s
  ", 
  $meta_key, 
  $meta_value
) );