tags:

views:

26

answers:

2

in mysql, if i have a query that returns something like

b-2; c-4, e-9

is there a way i could unite it with

a-0; b-0; c-0; d-0; e-0; f-0;

to get a final result

a0; b-2; c-4; d-0; e-9, f-0?

i understand that the better way to approach it is to rewrite the original query, but it is somewhat complex for my level (complete sql noob), and I'm rather pressed with time. thank you

A: 

Yes, you can inner join the two queries as subqueries and then add the counts.

select 
  letter,
  a.count + b.count as total
from (
   select letter, count(*)
   from blah blah lots of joins
   group by letter
) as a
inner join (
   select letter, count(*)
   from blah blah lots of joins
   group by letter
) as b
on a.letter = b.letter
Tom Ritter
The first query returns `b-2; c-4, e-9`, so an inner join might leave out the `a` row?
Andomar
So use a full outer join.
Tom Ritter
A: 

You can use a union. The first part of the union has the letters from the first query, and the second part the letters which the first part did not contain:

select * from query1
union all
select * from query2 b
where not exists (select * from query1 a where a.letter = b.letter)

If the query returns the entire field (a-0 instead of a), you'd have to use substring.

Andomar