我的SQL查询有什么问题

时间:2013-12-03 20:04:16

标签: mysql sql phpmyadmin

我喜欢它返回products_extrafield_id不是14的记录,但它仍然在我的结果中返回它...我正在使用连接

SELECT op. * 
FROM 
  products_to_products_extra_fields AS p
  INNER JOIN orders_products AS op ON p.products_id = op.products_id
  INNER JOIN orders AS o ON op.orders_id = o.orders_id
WHERE NOT 
EXISTS (

    SELECT * 
    FROM products_to_products_extra_fields
    WHERE
      p.products_id = op.products_id
      AND p.products_extra_fields_id = 14
  )
  AND o.date_purchased BETWEEN  '2013-11-29' AND  '2013-12-03 23:59:59'
  AND o.payment_method =  'Institutional Billing'
  AND o.orders_status <100001
GROUP BY o.orders_id
ORDER BY DECODE( o.cc_type,  'oFsAfHr7' ) ASC 
LIMIT 0 , 30

2 个答案:

答案 0 :(得分:3)

如果我正确读取您的SQL,那么您不需要NOT EXISTS子句来执行此操作。只需使用以下语句替换NOT EXISTS子句:p.products_extra_fields_id!= 14

SELECT 
    op. * 
FROM 
    products_to_products_extra_fields AS p
    INNER JOIN orders_products AS op 
    ON p.products_id = op.products_id
    INNER JOIN orders AS o 
    ON op.orders_id = o.orders_id
    WHERE 
        p.products_extra_fields_id != 14
    AND o.date_purchased BETWEEN  '2013-11-29' AND  '2013-12-03 23:59:59'
    AND o.payment_method =  'Institutional Billing'
    AND o.orders_status <100001
GROUP BY o.orders_id
ORDER BY DECODE( o.cc_type,  'oFsAfHr7' ) ASC 
LIMIT 0 , 30

答案 1 :(得分:0)

为什么不使用聚合函数进行GROUPing?另外,为什么会尝试GROUP BY不在SELECT中的字段?我添加了DISTINCT运算符,同时移动了你的逻辑。子查询使用了主/外查询中的条件。

SELECT DISTINCT o.cc_type, op.* 
FROM  orders_products AS op 
  INNER JOIN orders AS o 
    ON op.orders_id = o.orders_id
WHERE o.date_purchased BETWEEN  '2013-11-29' AND  '2013-12-03 23:59:59'
  AND o.payment_method =  'Institutional Billing'
  AND o.orders_status <100001
  AND NOT EXISTS (SELECT *
                  FROM products_to_products_extra_fields AS p
                  WHERE p.products_id = op.products_id
                    AND p.products_extra_fields_id = 14)
ORDER BY DECODE( o.cc_type,  'oFsAfHr7' ) ASC 
LIMIT 0 , 30;