2014-03-05 85 views
0
類別

組織總計考慮在MySQL數據庫中的以下表:MySQL的:從兩列由

表1:

+------+-----------+----------------------+ 
| id | atual | category_id | user | 
+------+-----------+--------------|-------+ 
| 1 | 100  | 1   | 1 | 
| 2 | 150  | 2   | 1 | 
| 3 | 50  | 1   | 2 | 
+------+-----------+--------------|-------+ 

表2:

+------+-----------+----------------------+ 
| id | budget | category_id | user | 
+------+-----------+--------------|-------+ 
| 1 | 100  | 2   | 1 | 
| 2 | 150  | 1   | 2 | 
| 3 | 50  | 1   | 1 | 
+------+-----------+--------------|-------+ 

表3:

+------+-----------+ 
| id | name | 
+------+-----------+ 
| 1 | one  | 
| 2 | two  | 
| 3 | three | 
+------+-----------+ 

我想計算表1和表2給出了給定用戶(在我的例子中爲1)中'atual'和'budget'的總和,按類別名稱排列:

我試過了下面的查詢,和預算不分類別:

SELECT table2.id, table3.name AS name_category, SUM(budget) , 
(SELECT SUM(atual) FROM table1 WHERE user =1) 
FROM table2 INNER JOIN table3 
ON table2.category_id=table3.id 

回答

2

這裏有一個方法:

select t3.id, t3.name, sum(actual) as actual, sum(budget) as budget 
from ((select category_id, sum(actual) as actual, NULL as budget 
     from table1 
     where user = 1 
     group by category_id 
    ) union all 
     (select category_id, NULL as actual, sum(budget) as budget 
     from table2 
     where user = 1 
     group by category_id 
    ) 
    ) ab join 
    table3 t3 
    on ab.category_id = t3.id 
group by t3.id, t3.name; 
+0

問題假設按類別組織,所以我認爲內查詢應該有GROUP BY CATEGORY_ID和「CATEGORY_ID」領域SELECT部分​​。 – StanislavL

+0

這看起來很奇怪,但它(幾乎)工作:它將添加按類別正確分組的實際值,但將所有預算值添加到單個類別中(儘管預算有幾個類別) –

+0

預算數字顯示爲總數實際數字爲空 –

1
SELECT t3.id, t3.name AS name_category, SUM(t2.budget) as budgety, SUM(t3.actual) as actual 
FROM table3 t3 
    LEFT OUTER JOIN table1 t1 on t1.category_id=t3.id 
    LEFT OUTER JOIN table1 t2 on t2.category_id=t3.id 
GROUP BY t3.id 
+0

感謝您的幫助。這將返回錯誤:#1064 - 您的SQL語法中有錯誤;檢查與您的MySQL服務器版本對應的手冊,以便在第3行的'OUTER JOIN table1 t2 on t'上的外部連接表t1上使用正確的語法 –

+0

更正答案 – StanislavL

+0

#1054 - 未知列'字段列表'中的't2.budget' –