值不在的值(子查询)

时间:2012-12-24 05:18:17

标签: mysql subquery

我一直在努力解决这个问题。 我有两张桌子。一个有优惠券和Invoicenumbers。一个有Invoicenumbers和客户名称。

我需要让那些没有使用过特定优惠券的顾客。

以下是表格:

促销表:

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

订单表:

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

所以杰克使用了优惠券A和B.而吉尔只使用了优惠券B.

如果我的查询是选择未使用优惠券A的客户,我应该获得Jill。

这有效,但看起来笨拙而缓慢。还有更好的方法吗?

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

感谢您的期待!

编辑: 这是一个SQLFiddle模式 http://sqlfiddle.com/#!2/21d31/6

4 个答案:

答案 0 :(得分:3)

 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

答案 1 :(得分:3)

已更新:我们应该使用prefer来为我们提供便捷的联接以获得更好的性能。 Join vs. sub-query

Sql Fiddle

Select distinct Customer from orders o
join 
(
  SELECT distinct Customer as changedname FROM Orders o2 
  join
  (
     Select distinct invoice from Promotions where Coupon='couponA'
  ) t3
  on o2.invoice = t3.invoice      
) t2
on o.customer != t2.changedname;

注意:我更改了t3的列名客户,因为两个连接的表必须具有不同的列名

<强>解释

当您拥有大数据时,使用内部或子查询会很昂贵。改为使用联接,让我们学习将子查询转换为加入

使用子查询我们有:

Select distinct Customer from orders where customer not in 
(SELECT distinct Customer FROM Orders where invoice in
(Select distinct invoice from Promotions where Coupon='couponA'));

第一步:

Select distinct Customer from orders o
join 
(
  SELECT distinct Customer as changedname FROM Orders where invoice in
  (Select distinct invoice from Promotions where Coupon='couponA')
) t2
on o.customer != t2.changedname;

第二步:

Select distinct Customer from orders o
join 
(
  SELECT distinct Customer as changedname FROM Orders o2 where invoice 
  join
  (
     Select distinct invoice from Promotions where Coupon='couponA'
  ) t3
  on o2.invoice = t3.invoice      
) t2
on o.customer != t2.changedname;

就是这样,对于有很多行的表来说要快得多

原始回答:

使用not in。看看。

Select distinct Customer from orders where customer not in 
(SELECT distinct Customer FROM Orders where invoice in
(Select distinct invoice from Promotions where Coupon='couponA'));

修改我添加了不同的内容以加快查询速度

SQL Fiddle

答案 2 :(得分:0)

请尝试此查询:

SELECT DISTINCT Customer
FROM Orders o1
WHERE NOT EXISTS (
    SELECT 1 
    FROM Orders o2
    INNER JOIN Promotions ON Promotions.Invoice = o2.Invoice
    WHERE o1.Customer = o2.Customer AND Coupon = 'couponB')

我们的想法是通过删除查询顶部的联接来摆脱GROUP BY,并通过创建协调子查询来消除NOT IN

Here is a link to sqlfiddle.

答案 3 :(得分:0)

尝试使用正确的联接

SELECT Customer, Coupon
FROM Promotions 
RIGHT JOIN Orders ON Promotions.Invoice = Orders.Invoice
    AND Coupon = 'couponA'
GROUP BY Customer
HAVING Coupon IS NULL