2013-10-03 252 views
1

假設我有一個產品表和選配項沒有在第二個表

id product 
1 Apple 
2 Bag 
3 Cat 
4 Ducati 

和車表的子集匹配

id user_id product_id 
1  1   2 
2  1   3 
3  2   1 
4  3   1 

所以,我想看一個特定的用戶,看看他/她沒有在他們的購物車中。

換句話說,在上面的例子中

SELECT ...... WHERE user_id=1 ..... 

將返回蘋果和杜卡迪因爲用戶1已經有袋和貓。

(這很可能複製到另外的問題,但有這麼多的變化我找不到確切的匹配,並把這些簡單的術語可能會有所幫助)

回答

2

執行左連接從產品到由用戶1購買的所有產品,它可以通過連接中的子選擇來檢索。這會導致所有不在user1護理中的產品ID具有空產品ID。 where子句將選擇所有null產品id的含義,它們不會存在於用戶購物車中,從本質上過濾購買的物品。

select p.name 
from product p 
left join (select product_id, user_id 
      from cart where user_id = 1) 
c 
on p.id = c.product_id 
where c.product_id is null; 

SQL小提琴:http://sqlfiddle.com/#!2/5318eb/17

+0

這是很好的做法,在你的答案添加關於您的解決方案,而不僅僅是代碼的一些細節。 –

+0

@RaduGheorghiu進入那部分。 –

+0

同意,更新! –

0
Select 
    * 
From Product p 
Where p.id Not In 
    (
     Select c.product_id 
     From Cart c 
     Where User ID = ____ 
    ) 
0
SELECT product FROM product_table 
WHERE product NOT IN 
(SELECT product_id FROM cart_table WHERE user_id = 1); 
0

這會給你所有的產品是在不在那裏購物車的所有用戶。

select c.user_id,a.Product 
from cart c Cross Join product a 
left Join 
cart b on b.product_id=a.id and c.user_id=b.user_Id 
where b.product_id is null 
group by c.user_id,a.Product 

Sql Fiddle Demo

相關問題