问题
I've been fighting this one for a couple of hours now and struggle with the proper MySQL syntax to use. Any pointer on the kind of SQL I'm looking for will be greatly appreciated.
Please consider those two simple tables:
purchase:
id email product_id
1 andy@aaa.com 1
2 bob@bar.com 2
3 charly@code.com 1
4 charly@code.com 2
subscriber:
id email name
1 andy@aaa.com Andy
2 bob@bar.com Bob
3 charly@code.com Charly
I'd like to select subscribers who did not buy product_id 1. ie: in this case, it should ONLY return Bob's row.
However, I'm currenty using this...
SELECT DISTINCT subscriber.*
FROM subscriber
LEFT OUTER JOIN purchase
ON subscriber.email = purchase.email
WHERE ( purchase.product_id <> 1 )
...which returns this:
id email name
2 bob@bar.com Bob
3 charly@code.com Charly
I understand that I need to handle the case of people showing up twice in the 'purchase' table. How can I do that?
Thank you for the pointers!
Fabien
回答1:
Just use the below:
SELECT DISTINCT subscriber.*
FROM subscriber
LEFT OUTER JOIN purchase
ON (subscriber.email = purchase.email and purchase.product_id = 1)
WHERE purchase.product_id IS NULL
回答2:
I think the easiest way is to consider the subscribers who did purchase the product -- and then filter them out. The following does this with a not exists
clause:
SELECT subscriber.*
FROM subscriber
where Not exists (select 1 from purchase where subscriber.email = purchase.email and purchase.product_id = 1)
来源:https://stackoverflow.com/questions/14968414/mysql-truly-distinct-join