Get products IDs by _sale_price_dates_to except or

2019-08-28 12:26发布

I'm using woocommerce and offer for woocommerce. And I want to get the products IDs without offers. I prepared the code but it doesn't work :( I tried in the second query: SELECT distinct(wp_postmeta.meta_value) ..., but it doesn't work, too.

$draftid = $wpdb->get_col('SELECT wp_posts.ID FROM ' . $wpdb->postmeta . ' join ' . $wpdb->posts . ' ON wp_posts.ID = wp_postmeta.post_id 
WHERE wp_posts.post_status="draft" and wp_postmeta.meta_key="_sale_price_dates_to" and wp_postmeta.meta_value != "" and wp_postmeta.meta_value<="' . (time()-1296000) . '"  
EXCEPT SELECT wp_postmeta.meta_value FROM ' . $wpdb->postmeta . ' join ' . $wpdb->posts . ' ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_postmeta.meta_key="orig_offer_product_id" and wp_postmeta.meta_value !="" and wp_posts.post_type="woocommerce_offer"'); print_r($draftid);

But separately the first query works, and the second too. If I use 'union' instead of 'except', it works too.

Any idea why?

1条回答
Juvenile、少年°
2楼-- · 2019-08-28 13:20

Try the following without any guaranty:

global $wpdb;

$draft_id = $wpdb->get_col("
    SELECT p.ID 
    FROM {$wpdb->prefix}posts as p
    JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id 
    WHERE p.post_status = 'draft' 
    AND pm.meta_key = '_sale_price_dates_to' 
    AND pm.meta_value ! = '' 
    AND pm.meta_value <= " . (time()-1296000) . "
    AND p.ID NOT IN (
        SELECT p2.ID 
        FROM {$wpdb->prefix}posts as p2
        JOIN {$wpdb->prefix}postmeta as pm2  ON p2.ID = pm2.post_id 
        AND pm2.meta_key = 'orig_offer_product_id' 
        AND pm2.meta_value ! = ''
        AND p2.post_type = 'woocommerce_offer'
    )
"); 

print_r($draft_id);

I hope it will work.

查看更多
登录 后发表回答