在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.
答案 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
答案 1 :(得分:1)
SELECT SUM(atual),
(SELECT SUM(budget) FROM table2 WHERE user=1)
FROM table1
WHERE user=1
答案 2 :(得分:0)
SELECT SUM(table1.atual) as Actual, SUM(table2.budget) as Budget
FROM table1, table2
WHERE table1.user=1