简体   繁体   English

如何在这种情况下加入3表?

[英]How to join 3 table with this condition?

I have 3 tables: product , customer and transaction . 我有3个表格: productcustomertransaction

Product: 产品:

id_product    price
    1         1000
    2         2000

Customer: 顾客:

id_customer    name
    1          Tom
    2          Jack

Transaction: 交易:

id_transaction    id_product     id_customer    qty    date
    1                 1              1           10    2013-02-21
    2                 2              1           50    2013-02-21
    3                 1              2           15    2013-02-21

I want to achieve this result: 我想要达到这个结果:

id_customer      name      total_transaction      purchase_qty      subtotal
    1            Tom             2                     60            110000
    2            Jack            1                     15             15000

How I can get that result using a query in MySQL? 如何在MySQL中使用查询获取结果?

SELECT  t.id_customer, c.name, 
        COUNT(t.id_customer) AS total_transaction, 
        SUM(t.qty) as purchase_qty
FROM transaction t
INNER JOIN customer c
ON t.id_customer = c.id_customer
GROUP BY t.id_customer,c.name
SELECT cs.id_customer, cs.name, COUNT(tr.transaction) AS total_transaction, SUM(tr.qty) as purchase_qty, SUM(tr.qty*pr.prize)
FROM customer AS cs
LEFT JOIN transaction AS tr ON tr.id_customer = cs.id_customer
LEFT JOIN product AS pr ON pr.id_product = tr.id_product
GROUP BY cs.id_customer

I suppose you are a total beginner, so I did this for you. 我想您是一个初学者,所以我为您做了。 Next time, if you have ANY own ideas, give to us, so we don't have to write the whole query for you. 下次,如果您有任何自己的想法,请给我们,这样我们就不必为您编写整个查询。 Show some effort. 付出一些努力。

SELECT c.id_customer, c.name, count(t.id_transaction) AS total_transaction
FORM Customer c INNER JOIN Transaction T
 ON C.id_customer = T.id_customer
GROUP BY c.id_customer

You need a group by statement since you want to aggregate results for a given customer : 您需要一个group by语句,因为您想汇总给定客户的结果:

SELECT id_customer, name, count(id_transaction) AS total_transaction
FORM Customer, Transaction
WHERE Transaction.id_customer = Customer.id_customer
GROUP BY id_customer

This does not solve your whole problem, but you've got the idea. 这不能解决您的整个问题,但是您已经有了主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM