首页 文章

SQL查询,了解每个用户购买产品的概况

提问于
浏览
1

我有三个表:用户,产品和购买

User: id, email
Product: id, name
Purchase: user_id, product_id, transaction_id

我的想法是,我可以找出任何给定用户他购买了哪些产品,以便(在我看来)我可以遍历所有产品并指出该用户已经购买了哪些产品 . 对于购买的产品,我会提出“看这个产品”,对于我想要显示“购买此产品”的所有其他产品 .

现在我正在使用以下查询,这是检索产品列表 for a given user

select p1.product_id as id, p2.name, p2.price, u1.id as user_id, p1.stripe_transaction_id 
from users u1
right join purchases p1 on u1.id = p1.user_id and u1.id = <user_id>
right join products p2 on p1.product_id = p2.id

基于此,我得到以下内容:

+------+---------------------+-------+---------+-----------------------+
| id   | name                | price | user_id | stripe_transaction_id |
+------+---------------------+-------+---------+-----------------------+
|  100 | Product 1           |  1999 |       3 | _jbshvScW_8961        |
|  100 | Product 1           |  1999 |    NULL | _zrtdXU_6811          |
|  101 | Product 2           |  1999 |       3 | _zvgvKS_2536          |
|  102 | Product 3           |  1999 |    NULL | _asgvMP_6811          |
|  103 | Bundle all products |  4999 |    NULL | _bffgMXX_6811         |
+------+---------------------+-------+---------+-----------------------+

此查询的问题在于它为product_id提供了多个条目(如果有更多人购买该产品将显示带有product_id的行,而user_id为NULL) . 在此特定示例中,另一个用户还购买了ID为100的产品 .

理想情况下,我得到以下(每个用户):

+------+---------------------+-------+-----------+-----------------------+
| id   | name                | price | purchased | stripe_transaction_id |
+------+---------------------+-------+-----------+-----------------------+
|  100 | Product 1           |  1999 |    false  | _zrtdXU_6811          |
|  101 | Product 2           |  1999 |    true   | _zvgvKS_2536          |
|  102 | Product 3           |  1999 |    false  | _asgvMP_6811          |
|  103 | Bundle all products |  4999 |    false  | _bffgMXX_6811         |
+------+---------------------+-------+-----------+-----------------------+

已经尝试了一段时间但没有到达那里 . 任何帮助表示赞赏!

3 回答

  • 2

    据我所知,您想输入一个user_id并获得他们可以购买的每件产品的输出,如果他们这样做的话 .

    如果是这样,您可以将用户CROSS JOIN加入产品,然后通过购买填写购买数据 . 但是CROSS JOIN很危险,容易捣乱,所以我避免了 .

    相反,为什么不直接使用产品数据并填写购买数据?

    SELECT
      p.id as product_id
      ,p.name
      ,p.price
      ,r.stripe_data
    FROM products p
    LEFT JOIN purchases r ON p.id = r.product_id AND r.user_id = <your user>
    

    这假定用户只能购买一次产品 .

  • 0

    您可以使用nested query而不是右连接,如下所示:

    select * from products where product_id in (select product_id from purchase where user_id = <user_id>)
    

    您还可以根据需要自定义结果视图以获取价格和其他数据 .

  • 0
    select prod.product_id as id, prod.product_name as name, prod.price as price,
    case when u.user_id is null then 'false' else 'true' end as pruchased,p.transcation_id
    from products prod left join purchases p on p.product_id=prod.product_id 
    left join users u on u.user_id = p.user_id and u.user_id=101;
    

相关问题