doukuang1897 2014-10-16 09:11
浏览 41
已采纳

WordPress / MySQL子查询问题

I am creating a shipping plugin for a client using wordpress and Woocommerce. I have an admin screen that displays all shipments with selectable filters, i.e date range, shipping carrier, service method, etc. I am able to query the database for records base on date range using the below code.

SELECT ID
FROM wp_posts
WHERE post_type LIKE 'shop_order'
AND ID = ANY
   (SELECT post_id
    FROM wp_postmeta
    WHERE meta_value
    BETWEEN DATE_SUB( NOW( ) , INTERVAL 30 DAY AND NOW( ) );
LIMIT 0 , 30

However, when I want to add another filter such as Carrier, ie 'USPS', an empty result is returned. When adding the following:

AND meta_value LIKE 'USPS' )

I am using $wpdb in my code, however, the above is a direct call in phpmyadmin.

  • 写回答

1条回答 默认 最新

  • drhozgt6007 2014-10-16 09:40
    关注

    I think the reason nothing is being returned is that you're trying to filter on a single meta value being both a date, and a carrier, at the same time:

    WHERE meta_value
      BETWEEN DATE_SUB( NOW( ) , INTERVAL 30 DAY AND NOW( )
      AND meta_value LIKE 'USPS'
    

    Instead, you could try something like:

    WHERE 
      ID IN 
      (
        SELECT post_id 
        FROM wp_postmeta 
        WHERE meta_key = 'date_key' 
          AND meta_value BETWEEN DATE_SUB( NOW( ) , INTERVAL 30 DAY AND NOW( ) )
      )
    AND
      ID IN 
      (
        SELECT post_id
        FROM wp_postmeta 
        WHERE meta_key = 'carrier_key' 
          AND meta_value = 'USPS'
      )
    

    Or joining to the meta table multiple times may be neater:

    SELECT ID
    FROM wp_posts
    INNER JOIN wp_postmeta meta_date ON wp_posts.ID = meta_date.post_id AND meta_date.meta_key = 'date_key'
    INNER JOIN wp_postmeta meta_carrier ON wp_posts.ID = meta_carrier.post_id AND meta_carrier.meta_key = 'carrier_key'
    WHERE post_type LIKE 'shop_order'
      AND meta_date.meta_value BETWEEN DATE_SUB( NOW( ) , INTERVAL 30 DAY AND NOW( ) )
      AND meta_carrier.meta_value = 'USPS'
    LIMIT 0 , 30
    

    As I don't know the meta keys you're using, you'd need to replace 'date_key' and 'carrier_key' with the correct values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理