Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE value IS NOT IN (subquery)

Tags:

mysql

subquery

I've been struggling with this query. I have two tables. One with coupons and Invoicenumbers. One with Invoicenumbers and customer names.

I need to get the customers who have not used a given coupon.

Here are the tables:

Promotion table:

Promotions
Invoice | Coupon
----------------
1       | couponA
2       | couponB
3       | couponB

Orders Table:

Orders
Invoice | Customer
------------------
1       | Jack
2       | Jack
3       | Jill

So Jack has used coupons A and B. And Jill has only used coupon B.

If my query were select customers who have not used coupon A, I should get Jill.

This works, but it seems clumsy and slow. Is there a better way?

SELECT Customer 
FROM Promotions INNER JOIN Orders
ON Promotions.Invoice = Orders.Invoice
WHERE Customer NOT IN(
    SELECT Customer 
    FROM Promotions INNER JOIN Orders
    ON Promotions.Invoice = Orders.Invoice
    WHERE Coupon = couponA)
GROUP BY Customer

Thanks for looking!

edit: Here's an SQLFiddle schema http://sqlfiddle.com/#!2/21d31/6

like image 454
TimSum Avatar asked Dec 24 '12 05:12

TimSum


1 Answers

 SELECT DISTINCT o2.customer FROM ORDER o2 
LEFT JOIN (promotions p1 
    JOIN Orders o1 ON p1.cuopon = 'CuoponA' AND p1.invoice = o1.invoice ) p3 
    ON o2.customer = p3.customer 
WHERE p3.customer IS NULL
like image 152
Akhil Avatar answered Oct 22 '22 20:10

Akhil