简体   繁体   中英

what's wrong with my sql query

Id like it to return records where products_extrafield_id is not 14 , but it still RETURNS it in my results .. I'm using joins

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

If I am reading your SQL correctly, then you don't need a NOT EXISTS clause to do this. Just replace the NOT EXISTS clause with the following statement: 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

Why are you GROUPing without using aggregate functions? Also, why would try to GROUP BY a field that is not in your SELECT? I added the DISTINCT operator, along with moving your logic around. You subquery was using criteria from the main/ outer query.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM