我一直在努力解决这个问题。 我有两张 table 。一张带有优惠券和发票编号。一个带有发票编号和客户名称。
我需要获取尚未使用给定优惠券的客户。
表格如下:
促销表:
Promotions
Invoice | Coupon
----------------
1 | couponA
2 | couponB
3 | couponB
订单表:
Orders
Invoice | Customer
------------------
1 | Jack
2 | Jack
3 | Jill
所以 Jack 使用了优惠券 A 和 B,而 Jill 只使用了优惠券 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
最佳答案
更新:我们应该更喜欢使用连接以获得更好的性能,因为它对我们来说很容易做到。 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 更改了列名 customer,因为两个连接表必须具有不同的列名
解释:
当您拥有大数据时,使用内部查询或子查询的成本很高。改为使用连接,让我们学习将子查询转换为连接
使用子查询我们有:
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;
就是这样,对于有很多行的表来说要快得多
原答案:
使用不在
。看看。
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'));
编辑 我添加了 distinct 以加快查询速度
SQL Fiddle
关于mysql - WHERE value IS NOT IN(子查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14017369/