2012-09-20 67 views
1

我有2個表,其中一個列出了'產品銷售',另一個列出了'產品價格'列表。MySql查詢 - 計算多個表的數字

**SALES** 
product_1 
product_1 
product_1 
product_2 

**PRICES** 
Product_1 | 10 
product_2 | 20 

我需要計算每個產品並將其乘以成本。

查詢應以下列格式給出結果:

NAME_________|______TOTAL 

PRODUCT1_____|______30 
PRODUCT2_____|______20 

任何幫助,不勝感激!

回答

3

使用它們的鏈接列(,特別是外鍵)加入兩個表,使用聚合函數SUM並按它們的名稱對它們進行分組。

SELECT a.name, SUM(b.price) as TotalPrice 
FROM sales a 
     INNER JOIN prices b 
      on a.name = b.name 
GROUP BY a.name 
+0

+1並祝賀20K :) – hims056

+0

@ hims056 gee thanks。 :d –