Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何使用此条件联接3个表?_Mysql_Sql - Fatal编程技术网

Mysql 如何使用此条件联接3个表?

Mysql 如何使用此条件联接3个表?,mysql,sql,Mysql,Sql,我有三个表:产品、客户和交易 产品: 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

我有三个表:
产品
客户
交易

产品:

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中使用查询获得该结果?

您需要一个
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
这并不能解决你的全部问题,但你已经有了这个想法

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个或更多的表时,您必须使用子查询或类似于客户的加入作为a,事务作为b。你怎么能只写transaction.id\u customer=customer.id\u customer?如果你不使用
作为
那么你可以使用你的表名作为标识这个查询不会产生所有需要的结果。我的错误是我以前从来没有使用过group,现在我使用我自己的查询(使用子查询not JOIN)我把分组放在旁边,它给出了我想要的结果。顺便说一句,谢谢你的建议。@AdvaitAmin总的来说,我知道如何做小计,但我只是忘了按分组(实际上我从来没用过)。所以,使用group by解决我的问题。@fenzkurol如果答案可以接受,什么时候它将满足提出问题的用户的所有要求。@AdvaitAmin是的,我知道了。顺便说一句,谢谢你的回复:)
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
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