具有多个表的复杂sql查询

时间:2012-06-19 07:11:14

标签: mysql sql

我有3张桌子:

客户

ID_CUSTOMER
NAME

产品

ID_PRODUCT
PRODUCTNAME
PRICE

订单

ID_ORDER
CUSTOMER_ID
PRODUCT_ID
QUANTITY

如何选择订购$ 10k或以上的所有客户?

4 个答案:

答案 0 :(得分:1)

select c.*
from customers c
inner join orders o on o.customer_id = c.id_customer
inner join products p on p.id_product = o.product_id
group by c.id_customer
having sum(p.price * o.quantity) >= 10000

答案 1 :(得分:1)

尝试类似:

SELECT C.ID_CUSTOMER, C.Name, 
      SUM(P.PRICE * O.QUANTITY) AS Total FROM Customers C 
      JOIN Orders O ON C.CUSTOMER_ID = O.CUSTOMER_ID
      JOIN Procucts P ON P.PRODUCT_ID = O.PRODUCT_ID
      GROUP BY C.ID_CUSTOMER, C.Name
      HAVING SUM(P.PRICE * O.QUANTITY) >= 10000

答案 2 :(得分:1)

试试这个:

 SELECT   a.ID_CUSTOMER, 
          a.NAME
   FROM   CUSTOMERS a
            INNER JOIN ORDERS b 
              ON b.CUSTOMER_ID = a.ID_CUSTOMER
            INNER JOIN PRODUCTS c
              ON c.ID_PRODUCT = b.product_id
GROUP BY  a.ID_CUSTOMER, a.NAME
  HAVING  SUM(c.PRICE * b.QUANTITY) >= 10000

答案 3 :(得分:1)

这不是一个复杂的查询。另一种做同样事情的语法:

SELECT C.ID_CUSTOMER, C.NAME, SUM(P.PRICE * O.QUANTITY) TOTAL
  FROM Products P, Customers C, Orders O
 WHERE O.CUSTOMER_ID = C.ID_CUSTOMER 
   AND O.PRODUCT_ID = P.ID_PRODUCT
 GROUP BY C.ID_CUSTOMER, C.NAME
HAVING SUM(P.PRICE * O.QUANTITY) >= 10000