2014-03-18 70 views
1

我有3个查询,第一个是这样的在MySQL计算多个查询

SELECT amount FROM table1 
WHERE id = "1" 

的这个输出是

amount 
10000 

然后我的第二个查询

SELECT SUM(hours * 10) as hours FROM table2 
WHERE empid = "1" 

输出是

hours 
400 

,然后我的第三个查询

SELECT totalcost FROM table3 
WHERE id = "1" 

输出

totalcost 
5000 

我加了第二和第三个查询

SELECT 'SUMQ2Q3', 
(SELECT SUM(hours * 10) as hours FROM table2 
WHERE empid = "1") 

+ 

(SELECT totalcost FROM table3 
WHERE id = "1") 

的价值,并得到了

5400 
输出

我希望发生的下一件事是减去第一个查询的值,当我总结第二个和第三个查询时得到的输出。 但我一直在得到一个语法错误。它目前看起来像这样

SELECT amount FROM table1 
WHERE id = "1" 

- 

SELECT 
(SELECT SUM(hours * 10) as hours FROM table2 
WHERE empid = "1" 

+ 

SELECT totalcost FROM table3 
WHERE id = "1") 

如何正确的方式来做到这一点?

+0

只需编写'WHERE id = 1'来进行整数比较。 – hjpotter92

回答

2

遗憾的是没有DB在这里,但

SELECT t1.amount - t2.sum + t3.totalcost 
FROM (SELECT amount FROM table1 WHERE id = "1") as t1, 
    (SELECT SUM(hours * 10) as hours FROM table2 WHERE empid = "1") as t2 
    (SELECT totalcost FROM table3 WHERE id = "1") as t3 

可能做的工作。

+0

我这样做,只是改变了它'SELECT t1.amount - (t2.sum + t3.totalcost)'它的工作。谢谢! :d – hearmeroar

0

如何试图

SELECT 
    (SELECT amount FROM table1 WHERE id = "1") 
    - (SELECT SUM(hours * 10) as hours FROM table2 WHERE empid = "1") 
    - (SELECT totalcost FROM table3 WHERE id = "1") 
0
SELECT (
(
SELECT amount FROM table1 WHERE id = "1") As x - 
(SELECT SUM(hours * 10) as hours FROM table2 WHERE empid = "1") As y + 
(SELECT totalcost FROM table3 WHERE id = "1") As z 
) 
As answer