2014-04-02 71 views
0

我有3個表,我想加入到輸出的單個行詳細報價號,客戶名稱和訂單總數..加入報價,訂單和客戶表?

TBL_QUOTATIONS

quotation_id  | customer_id | status  
-----------------+-----------------+--------------- 
1038     21     Open 
1039     22     Open  

TBL_CUSTOMERS

customer_id  | name   | status  
-----------------+-----------------+--------------- 
21     David    Active 
22     Alvin    Active  

TBL_ORDERS

order_id  | quote_id | desc    | amount 
-------------+--------------+---------------------+------------- 
1     1038   Consultation   1500 
2     1038   Design Fees   1200 
3     1038   Misc Fees    500 

需要幫助拿到語句正確做到以上......目前我使用

SELECT tbl_quotations.quote_id,customers.customer_id,姓名,金額(量) FROM tbl_quotations INNER JOIN客戶ON tbl_quotations.customer_id = tbl_customers.customer_id 加入訂單ON tbl_quotations.quote_id = tbl_orders.quote_id

結果

quote_id  | customer_name | sum(amount)    
-------------+-------------------+------------------- 
1038    David    3200    
1039    Alvin     0 
.     .     . 
.     .     . 
.     .     . 

我不知道我哪裏錯了,但很明顯的語句僅返回即使你有在數據庫中更多的報價一行。

任何幫助或建議我出錯的地方?我的方法更合適嗎? 謝謝!

+1

你需要'GROUP BY tbl_quotations.quote_id'。 – Vatev

+0

謝謝你,作品像一個魅力! – user3448267

回答

1

嘗試

SELECT tbl_quotations.quote_id, customers.customer_id, name, sum(amount) 
FROM tbl_quotations INNER JOIN customers ON tbl_quotations.customer_id = tbl_customers.customer_id Join orders ON tbl_quotations.quote_id = tbl_orders.quote_id 
GROUP BY tbl_quotations.quote_id