tags:

views:

262

answers:

4

I am trying to fetch the sum of several counts in one query:

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

I am missing something here. I get syntax error.

+8  A: 
SELECT ( SELECT COUNT(*) FROM comments ) 
     + ( SELECT COUNT(*) FROM tags ) 
     + ( SELECT COUNT(*) FROM search )
Matt Rogish
Yes, exactly. Note: in Oracle, you have to add " from dual" to that syntax.
Bruno Rothgiesser
+1 Very nice, I'd do it this way.
Zack
+1  A: 
SELECT (
       SELECT  COUNT(*)
       FROM    comments
       ) +
       (
       SELECT  COUNT(*)
       FROM    tags
       ) +
       (
       SELECT  COUNT(*)
       FROM    search
       )
Quassnoi
+5  A: 

One more (not sure if supported with MySQL, though - works in 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
Ken White
Curious - what are the pros/cons of each of yours and the accepted answers' SQLs? Is one better in terms of performance? Something else?
Liao
To Liao: Run the query analyzer and see what it says. They may be synonymous.
Mark Canlas
Very nice. +1 for elegancy of SQL statement(s).
Zack
They should be the same; I like mine because it's far less typing. :D
Matt Rogish
@Matt: Ah, yes! A man after my own heart - lazy! <g> Mine comes from having to explain it to non-tech people all the time; the extra keystrokes lessen the verbiage of the explanation. :-)
Ken White
@Zack: Thanks. :-)
Ken White
+1  A: 
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
    )
n8wrl
should be union all
dotjoe
@dotjoe: Good catch!
n8wrl
@ n8wrl: Beat you by a few minutes. <g> Besides dotjoe's catch, and just FYI, the column alias is only required in the first subselect, as it's ignored in the other three during the union operation.
Ken White
@Ken: Thanks for that. What i was really after was the syntax that allowed me to refer to the first column in the sum() regardless of its name. NO joy.
n8wrl