选择...不存在的地方

时间:2016-03-29 09:28:43

标签: php sql wordpress select not-exists

我尝试制作自定义查询以从wordpress获取帖子(他们真的是产品),其中没有名为' custom_code&#39的元查询; 即可。 我正在尝试:

SELECT DISTINCT p.ID
FROM
    wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
    p.post_type = 'product'
AND ( p.post_status = 'publish' OR p.post_status = 'draft' )
AND pm.meta_key = 'custom_code' AND pm.meta_key IS NULL

我尝试使用NOT EXISTS,但是sql返回错误:

SELECT DISTINCT p.ID
FROM
    wp_posts p
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
    p.post_type = 'product'
AND ( p.post_status = 'publish' OR p.post_status = 'draft' )
AND NOT EXISTS (
    select * from wp_postmeta as pm2
    where pm2.meta_key = 'custom_code'
)

注意:我需要获得具有状态'发布'作为状态为' draft'。

的帖子

错误返回

无法识别的关键字。 (靠近" NOT",位置193)

无法识别的关键字。 (近#34; EXISTS",位置197)

符号(令牌)意外。 (靠近"("在204位)

当前要点

我使用了WordPress API,但它确实有效,但我需要添加一个LEFT JOIN来获取名称类似于下面句子返回的每个产品名称的产品。这是一句话:

$args = array(
   'posts_per_page'   => -1,
   'post_type'      =>'product',
   'post_status'      => 'publish,draft',
   'meta_query' => array(
               array(
                 'key' => 'custom_code',
                 'compare' => 'NOT EXISTS'
              )),
);
$posts_array = get_posts( $args );

有任何帮助吗? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

这是NOT EXITSTS的查询可能是:

SELECT DISTINCT p.ID
FROM wp_posts AS p
WHERE p.post_type = 'product' AND 
      p.post_status ΙΝ ('publish', 'draft' ) AND 
      NOT EXISTS (select * 
                  from wp_postmeta as pm
                  where p.ID = pm.post_id AND 
                        pm.meta_key = 'custom_code')

或使用LEFT JOIN

SELECT DISTINCT p.ID
FROM wp_posts AS p
LEFT JOIN wp_postmeta AS pm 
   ON p.ID = pm.post_id AND pm.meta_key = 'custom_code'
WHERE p.post_type = 'product' AND 
      p.post_status ΙΝ ('publish', 'draft' ) AND 
      pm.post_id IS NULL    

答案 1 :(得分:1)

你有没有试过这样的东西

$args = array(
   'posts_per_page'   => -1,
   'post_type'      =>'product',
   'post_status'      => 'publish,draft',
   'meta_query' => array(
               array(
                 'key' => 'custom_code',
                 'compare' => 'NOT EXISTS'
              )),
);
$posts_array = get_posts( $args );

var_dump( $posts_array );

注意

使用此代码打印查询

global $wpdb;
var_dump( $wpdb->last_query);