sql查询来自order itemmeta表的2个meta键

i7uq4tfw  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(307)

我目前有一个sql查询来调用特定产品类型的所有订单id,但是我现在需要它来调用也有特定元键的订单,只要它有一个元键,这个键的值就会随着每个购买的商品而增加。

function get_last_order_id_from_product( $product_id ) {

    global $wpdb;

    $results = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value = '$product_id'
        AND order_item_meta.meta_key = 'Ticket Number'
        ORDER BY order_items.order_id DESC LIMIT 1, 1
    ");

    return $results;
}

我假设它已经使用同一个调用变量调用了一个元键,但是当调用函数时,它只会在woocommerce中给我一个内部服务器错误。有问题的元键是

AND order_item_meta.meta_key = 'Ticket Number'
1qczuiv0

1qczuiv01#

你需要 JOIN 另一次是在餐桌上 wp_woocommerce_order_itemmeta 使用它自己的引用,当您在该表上查询两次不同的元键时,请尝试以下操作:

function get_last_order_id_from_product( $product_id ) {
    global $wpdb;

    return $wpdb->get_col( $wpdb->prepare( "
        SELECT oi.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as oi
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as oim
            ON oi.order_item_id = oim.order_item_id
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as oim2
            ON oi.order_item_id = oim2.order_item_id
        LEFT JOIN {$wpdb->posts} AS p
            ON oi.order_id = p.ID
        WHERE p.post_type = 'shop_order'
        AND oi.order_item_type = 'line_item'
        AND oim.meta_key = '_product_id'
        AND oim.meta_value = '%d'
        AND oim2.meta_key = 'Ticket Number'
        ORDER BY oi.order_id DESC
        LIMIT 1, 1
    ", $product_id ) );
}

测试和工作。

相关问题