mysql subselect query - 查找所有具有'failed'状态的订单WOOCOMMERCE

时间:2015-02-10 19:44:27

标签: mysql sql database woocommerce

我正在尝试查找状态为“失败”的所有订单

每个查询都单独工作,但当我使用一个作为子查询时,它会失败。

 SELECT wp_posts.*
        FROM wp_postmeta
        INNER JOIN wp_posts
        ON wp_postmeta.post_id = wp_posts.ID
        AND wp_posts.post_type='shop_order'
        AND wp_posts.post_status='publish'
        AND wp_posts.post_date>='{$this->carbon->now()->subDays($days)->toDateTimeString()}'
        AND wp_postmeta.meta_key='_customer_user'
        AND wp_postmeta.meta_value='{$this->user->ID}'
        IN (SELECT DISTINCT wp_postmeta.post_id, tt.taxonomy, te.slug 
        FROM wp_postmeta, wp_terms te, wp_term_relationships tr, wp_term_taxonomy tt
          WHERE wp_postmeta.post_id = tr.object_id
          AND tr.term_taxonomy_id = tt.term_taxonomy_id
          AND te.term_id = tt.term_id
          AND tt.taxonomy = 'shop_order_status'
          AND te.slug = 'failed'
        )

我对sql很新,所以我认为子查询是错误的。子查询甚至有意义吗?我正在寻找具有这些条件的帖子,然后进行另一个查询以找到te.slug值为'failed'的帖子

感谢您提供任何指导。

3 个答案:

答案 0 :(得分:0)

在子查询中,确保只选择一列。这将解决您的问题。此外,您似乎错过了AND some_column IN ...。你只有IN

答案 1 :(得分:0)

  1. 已转换,将样式连接到内部联接样式表示法
  2. 之前添加了AND wp_Postmeta.Post_ID
  3. 仍在评估是否有更好的方法来避免使用..
  4. SELECT wp_posts.*
    FROM wp_postmeta
    INNER JOIN wp_posts
      ON wp_postmeta.post_id = wp_posts.ID
      AND wp_posts.post_type='shop_order'
      AND wp_posts.post_status='publish'
      AND wp_posts.post_date>='{$this->carbon->now()->subDays($days)->toDateTimeString()}'
      AND wp_postmeta.meta_key='_customer_user'
      AND wp_postmeta.meta_value='{$this->user->ID}'
      AND wp_Postmeta.Post_ID IN (
        SELECT DISTINCT wp_postmeta.post_id, tt.taxonomy, te.slug 
        FROM wp_postmeta
        INNER JOIN wp_term_relationships tr
          ON wp_postmeta.post_id = tr.object_id 
        INNER JOIN wp_term_taxonomy tt
          ON tr.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN wp_terms te
          ON te.term_id = tt.term_id
        WHERE tt.taxonomy = 'shop_order_status'
          AND te.slug = 'failed')
    

答案 2 :(得分:0)

这可能是你正在尝试的;

SELECT ps.*
        FROM wp_postmeta pm, wp_posts ps
        WHERE wp_pm.post_id = ps.ID
        AND ps.post_type='shop_order'
        AND ps.post_status='publish'
        AND ps.post_date>='{$this->carbon->now()->subDays($days)->toDateTimeString()}'
        AND pm.meta_key='_customer_user'
        AND pm.meta_value='{$this->user->ID}'
        AND EXISTS (SELECT 1
        FROM wp_terms te, wp_term_relationships tr, wp_term_taxonomy tt
          WHERE pm.post_id = tr.object_id
          AND tr.term_taxonomy_id = tt.term_taxonomy_id
          AND te.term_id = tt.term_id
          AND tt.taxonomy = 'shop_order_status'
          AND te.slug = 'failed'
        )