I am working on some trending/analysis tools, and would like to query the events MySQL database for an events per hour metric so that I can send the metric out as a datapoint in graphite. Because some events will be in the status table, while others in the history table, I came up with the basic query I am looking for. Keeping in mind, that I am by no means a DBA, I would like to learn how to get a total count from both tables. Here is what I have so far:
mysql> SELECT COUNT(*) FROM events.history WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
-> UNION
-> SELECT COUNT(*) FROM events.status WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
-> ;
+----------+
| COUNT(*) |
+----------+
| 27 |
| 267 |
+----------+
2 rows in set (0.00 sec)
mysql>
I am hoping to modify the SQL to return a single row, with the count from both tables added, so in the example it would be 294. Somebody told me that I can accomplish this with a join, but I seem to be having some trouble getting the syntax dialed in.
Put the union in a subquery and then use SUM()
to add them together.
SELECT SUM(c) total
FROM (SELECT COUNT(*) c FROM events.history WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
UNION
SELECT COUNT(*) c FROM events.status WHERE firstTime > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND (severity='5' OR severity='3')
) u