Opdateret: Vi bør bruge foretrækker at bruge joins for bedre ydeevne, når det er nemt at gøre for os. Deltag vs. underforespørgsel
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;
Bemærk:Jeg har ændret kolonnenavnkunde for t3, fordi to sammenføjede tabeller skal have forskellige kolonnenavne
Forklaring:
Det er dyrt at bruge indre eller underforespørgsler, når du har big data. brug joins i stedet, lad os lære at konvertere underforespørgsel til join
Med Underforespørgsel Vi havde:
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'));
Konverterer underforespørgsel til at deltage
Første trin:
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;
2. trin:
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;
Og det er det, meget hurtigere for tabeller med adskillige rækker
Oprindeligt svar:
Brug not in
. Tag et kig.
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'));
Rediger Jeg har tilføjet distinkt for at gøre forespørgslen hurtigere