MySQL “truly distinct” join

Deadly 提交于 2019-12-11 15:09:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!