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

时间:2013-02-21 10:38:24

标签: mysql sql

我有3个表:productcustomertransaction

产品:

id_product    price
    1         1000
    2         2000

客户:

id_customer    name
    1          Tom
    2          Jack

交易:

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

我想达到这个结果:

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

如何使用MySQL中的查询获得该结果?

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

我想你是一个初学者,所以我为你做了这个。下次,如果您有任何想法,请给我们,所以我们不必为您编写整个查询。显示一些努力。

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

您需要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

这并不能解决你的整个问题,但你已经明白了。