2014-03-05 130 views
-1

在MySQL中獲取總計,我要查詢兩個表:MySQL查詢:從兩個非關聯表

表1:

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

表2:

+------+------------+-------+ 
| id | budget | user | 
+------+------------+-------+ 
| 1 | 80  | 3 | 
| 2 | 150  | 1 | 
| 3 | 200  | 2 | 
+------+------------+-------+ 

我要搶用戶1的總數。

兩個表格不相關。不過,他們擁有共同的用戶密鑰。

這是我的嘗試:

SELECT SUM(atual), SUM(budget) 
FROM table1, table2 
WHERE user=1 

這是產生錯誤:

#1630 - FUNCTION SUM does not exist. 

回答

1
SELECT SUM(atual), 
    (SELECT SUM(budget) FROM table2 WHERE user=1) 
FROM table1 
WHERE user=1 
+0

請注意:如果'table2'中的用戶不在'table1'中,這將不起作用。 –

0
SELECT SUM(table1.atual) as Actual, SUM(table2.budget) as Budget 
FROM table1, table2 
WHERE table1.user=1 
+0

#1052 - 在where子句是不明確的列「用戶」 –

+0

對不起表都具有用戶現場,所以你必須使用從您希望的表的名稱用戶被採取。 –

1

您需要join之前做了彙總:

select a.actual, b.budget 
from (select sum(actual) as actual from table1) a cross join 
    (select sum(budget) as budget from table2) b; 

編輯:

當你在一個問題中說「兩個表格不相關」時,它肯定會顯示你不關心用戶列。我覺得你真的想這樣:

select user, sum(actual) as actual, sum(budget) as budget 
from ((select user, sum(actual) as actual, NULL as budget 
     from table1 
     group by user 
    ) union all 
     (select user, NULL as actual, sum(budget) as budget 
     from table2 
     group by user 
    ) 
    ) ab 
group by user 
+0

謝謝,但我在哪裏指定用戶代碼? –