在Mysql中添加两个不同查询的结果

时间:2012-03-26 20:12:41

标签: mysql

我在编写查询时遇到问题。我一直在与UNION合作进行两次查询,他们的工作正常。当我尝试添加两个查询的结果时,我的问题出现了。

这是我自己解释的事情。

//Query 1
select count(id) from table1   <-- This gives a result of 2 
//Query 2
select count(id) from table2   <-- This gives a result of 1


//What I want to do is to add the two queries (2 + 1 = 3):
(select count(id) from table1) + (select count(id) from table2) <-- Which gives a result of 3.

执行此查询时,会出现此错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+ 

我想我不应该使用“+”符号。有没有办法做到这一点? 非常感谢你!

2 个答案:

答案 0 :(得分:4)

您应该在整个查询周围使用SELECT:

SELECT (SELECT COUNT(id) FROM table1) + (SELECT COUNT(id) FROM table2) AS count

答案 1 :(得分:1)

尝试

SELECT (select count(id) from table1) + (select count(id) from table2) from dual;