【问题标题】:MySQL LIKE statement supporting multiple queries支持多个查询的 MySQL LIKE 语句
【发布时间】:2018-08-25 00:32:33
【问题描述】:

希望使用部分匹配来查找产品名称,例如,如果 product_namecat-in-the-hat 并且 namecat,那么 @ 987654325@ 将被退回。目前,需要完全匹配,即部分匹配是不可能的。

LIKE 语句通常可以工作,但我们使用IN 语句来支持不同数量的输入。根据MySQL LIKE IN()?REGEXP 也应该可以工作,但如前所述,输入的数量会有所不同。为每个 name 实例执行匹配的理想方法是什么?

function woo_products_by_name_shortcode( $atts, $content = null ) {

    // Get attribuets
    extract(shortcode_atts(array(
        'name' => ''
    ), $atts));

    if( empty($name) ) return;

    // Format product slugs string
    $name = str_replace(",", "','", $name);

    global $wpdb;
    // Get the corresponding products ids for each name
    $ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts
        WHERE post_type = 'product' AND post_name IN('$name')" );

    ob_start();

    // Define Query Arguments
    $loop = new  WP_Query( array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'post__in'       => $ids
    ));

    // Get products number
    $product_count = $loop->post_count;

    echo '<pre>'; print_r($loop->posts); echo '</pre>';

    return ob_get_clean();
}
add_shortcode("woo_products_by_name", "woo_products_by_name_shortcode");

【问题讨论】:

  • 你考虑过只用WHERE &lt;condition&gt; OR &lt;condition&gt; ...吗?
  • 这将对您有所帮助:stackoverflow.com/questions/907806/…
  • @fubar,是的,请查看链接的问题。就我而言,我不知道会有多少条件。 @anonyXmous 不是您引用的类似我已经在做的事情吗?问题是我需要为每个 IN 匹配支持 LIKE 匹配。
  • 这应该不是问题。你的条件会在一个数组中吗?

标签: mysql wordpress


【解决方案1】:

我无法根据Array in Mysql WHERE LIKE? 解决。以下是我如何使它工作:

$array_name = explode(",", $atts['name']);

global $wpdb;
// Get the corresponding products ids for each name
$query_parts = array();
foreach ($array_name as $val) {
    $query_parts[] = "'%%".$val."%%'";
}

$string = implode(' OR post_name LIKE ', $query_parts);
$ids = $wpdb->get_col($wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts
    WHERE post_type = 'product' AND post_name LIKE {$string}" ));

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 2010-12-19
    • 2016-01-04
    • 2012-11-20
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多