Previous question linky: MySQL Left Joins
Very kindly we got the following code working:
select
JustACME.Name,
JustACME.NameCount,
COALESCE( COUNT( * ), 0 ) as CountFromResultsTable
from
( select a.Name,
count(*) as NameCount
from
acme a
group by
a.Name ) JustACME
LEFT JOIN results r
on JustACME.Name = r.Name
group by
JustACME.Name
The above code works exactly as we need and brings back the following
Name Count Total
Tom 10 5
Bon 9 4
In addition to that information being in the acme and results table, we also need to bring back further information. The ‘results’ table is as follows:
Name q1
Tom 1
Tom 2
Tom 1
Bob 3
Bob 2
Bob 1
Bob 2
I’d like to add to this query, in the talble called results there is another field called q1. This can have a number in it, either 1, 2, or 3 – what I’d like to do is bring back the number of times that 1,2 or 3 appears (count) for each of the Name that also appear in the table. Make sense?
Basically, the output of the query should be something like this:
Name Count Total q1 = 1 q1 = 2 q1 = 3
Bob 9 4 1 2 1
Tom 10 5 4 1 0
I’m probably going out on a limb here but can it be done???
Thanks in advance,
H.
To get just the
Name, q1=1, q1=2, q1=3table fromresultsonly you can use:This counts up the number of occurences of each result (per Name) — this works because you only want three extra columns and know inadvance which values of q1 you want to have a columns. (If there were say half a million q1 values there’s no way to do this in MySQL other than writing out the
COUNT(IF(q1=i,1,0)) AS q1isihalf a million times — not exactly ideal).To combine with your previous query, perhaps something like this (add it in as a
JOIN):In fact, I’m sure there’s a way to do this without needing to
LEFT JOINon a sub-query, but my mysql kung fu has run out 😛