添加几个COUNT个查询的结果

时间:2009-07-21 17:16:36

标签: sql mysql

我试图在一个查询中获取几个计数的总和:

SELECT(
    SELECT COUNT( * )
    FROM comments +
    SELECT COUNT( * )
    FROM tags +
    SELECT COUNT( * )
    FROM search
)

我在这里遗漏了一些东西。我收到语法错误。

4 个答案:

答案 0 :(得分:16)

SELECT ( SELECT COUNT(*) FROM comments ) 
     + ( SELECT COUNT(*) FROM tags ) 
     + ( SELECT COUNT(*) FROM search )

答案 1 :(得分:6)

还有一个(不确定是否支持MySQL,但是 - 在SQL Server中有效):

SELECT SUM(Counts) FROM
  (SELECT COUNT(*) AS Counts FROM COMMENTS UNION ALL
   SELECT COUNT(*) FROM Tags UNION ALL
   SELECT COUNT(*) FROM Search) s

答案 2 :(得分:2)

SELECT (
       SELECT  COUNT(*)
       FROM    comments
       ) +
       (
       SELECT  COUNT(*)
       FROM    tags
       ) +
       (
       SELECT  COUNT(*)
       FROM    search
       )

答案 3 :(得分:2)

SELECT SUM(ThisCount)
  FROM (
    SELECT COUNT(*) AS ThisCount
      FROM comments

    UNION ALL

    SELECT COUNT(*) AS ThisCount
      FROM tags

    UNION ALL

    SELECT COUNT(*) AS ThisCount
      FROM search
    )