2

假设我有一个 Product 表和一个

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 .....  

将返回 Apple 和 Ducati,因为用户 1 已经拥有 Bag 和 Cat。

(这很可能会重复另一个问题,但是有很多变体我找不到完全匹配的内容并输入这些简单的术语可能会有所帮助)

4

4 回答 4

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

于 2013-10-03T09:07:10.173 回答
0
Select
  * 
From Product p
Where p.id Not In
    (
        Select c.product_id
        From Cart c
        Where User ID = ____
    )
于 2013-10-03T09:10:50.347 回答
0
SELECT product FROM product_table 
WHERE product NOT IN
(SELECT product_id FROM cart_table WHERE user_id = 1);  
于 2013-10-03T09:11:01.907 回答
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 小提琴演示

于 2013-10-03T09:21:50.000 回答