2013-02-19 126 views
0

我一直在争取这一个几个小时,并与适当的MySQL语法使用斗争。任何我正在寻找的SQL类型的指针将不胜感激。MySQL“真正独特”的加入

请考虑这两个简单的表:

purchase: 
id email product_id 
1 [email protected] 1 
2 [email protected]  2 
3 [email protected]  1 
4 [email protected]  2 

subscriber: 
id email name 
1 [email protected] Andy 
2 [email protected]  Bob 
3 [email protected]  Charly 

我想选择谁做买的product_id 1. 即用户:在这种情况下,它应该只返回B​​ob的一行。

不过,我currenty使用此...

​​

...返回此:

id email name 
2 [email protected]  Bob 
3 [email protected]  Charly 

我明白,我需要处理的人的情况下显示了两次在'购买'表中。我怎样才能做到这一点?

谢谢指点!

法比安斯基

回答

3

只需使用如下:

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 
+0

感谢。不是工作,它让我深入挖掘和理解JOIN更好! – 2013-02-20 17:16:10

0

我认为最简单的方法是考虑谁购买该产品订户 - 然后筛选出来。下面这是否与not exists条款:

SELECT subscriber.* 
FROM subscriber 
where Not exists (select 1 from purchase where subscriber.email = purchase.email and purchase.product_id = 1)