Tag Archives: MySQL

Summing Union’d Counts

I ran across this funkiness in a MySQL query the other day. If anyone knows why the following is, please comment.

This query doesn’t work:

SELECT SUM(v.vehicle_count) AS total_vehicles FROM (
    SELECT COUNT(c.id) AS vehicle_count FROM cars AS c
    UNION
    SELECT COUNT(t.id) AS vehicle_count FROM trucks AS t
) AS v

But including another field in the subqueries, like ‘model’ below, does:

SELECT SUM(v.vehicle_count) AS total_vehicles FROM (
    SELECT COUNT(c.id) AS vehicle_count, c.model FROM cars AS c
    UNION
    SELECT COUNT(t.id) AS vehicle_count, t.model FROM trucks AS t
) AS v