【问题标题】:select ... where not exists选择 ... 不存在的地方
【发布时间】:2016-07-16 18:36:58
【问题描述】:

我正在尝试进行自定义查询以从 wordpress 中获取帖子(它们实际上是产品),其中 没有名为“custom_code”的元查询。 我正在尝试:

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'
)

注意:我需要将状态为“发布”的帖子作为状态为“草稿”的帖子。

错误返回

无法识别关键字。 (在“NOT”附近,位置 193)

无法识别关键字。 (在“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 );

有什么帮助吗? 提前致谢。

【问题讨论】:

  • 将 WHERE 更改为 AND。将最后的 AND 更改为 WHERE。
  • 那么 meta_key 不能同时是 'custom_code' AND NULL。您应该添加您观察到的错误消息。
  • @DanielGarciaSanchez 我认为如果您翻译错误消息会更具可读性。我(例如)无法理解西班牙语/葡萄牙语/...

标签: php sql wordpress select not-exists


【解决方案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);

【讨论】:

  • 是的,我做到了,它工作正常,但我需要在 sql 代码中添加左连接,以获取名称类似于返回的每个产品的名称的产品,但没有自定义代码
【解决方案2】:

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    

【讨论】:

  • 我尝试了你的 NOT EXITSTS 语句,但是 sql 返回了我在帖子中添加的错误。
  • @DanielGarciaSanchez 据我所知,该查询在语法上是正确的。
猜你喜欢
  • 2010-10-29
  • 2016-05-20
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多