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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s