I've got this query that isn't giving me the corrent count on instances. Basically it is supposed to count the number of times a specific ID number appears in the table. Here's the query:
$query_popular = "select b.*, (count(t1.first_bar) + count(t2.second_bar) + count(t3.third_bar)) as 'bar_count'
from barlist b
left join userdestinations t1 on b.id = t1.first_bar
left join userdestinations t2 on b.id = t2.second_bar
left join userdestinations t3 on b.id = t3.third_bar
where b.city = '$city'
group by b.id order by bar_count desc";
$popular = mysql_query($query_popular, $connBarHopper) or die(mysql_error());
$row_popular = mysql_fetch_assoc($popular);
Where userdestinations has 5 fields: email, first_bar, second_bar, third_bar, and date. Each bar field is the ID number of a bar from the barlist table. Date is in the form date("Ymd"), although I don't think that matters.
I have 4 entries in the userdestinations table:
address1 5 4 1 20051118
address1 1 5 2 20050626
address1 1 4 5 20051122
address2 5 20051122
Notice that the last entry has a blank field for both second_bar and third_bar.
When I display b.id and bar_count in a table using a do while loop with mysql_fetch_assoc in the while part, I get the following results:
id bar_count
5 6
1 4
4 2
2 1
As you can see from the actual values in the table, the count I want should be
5 4
1 3
4 2
2 1
I admit I don't completely understand what the above code does entirely because I got it from someone who responded to another question I had, and then I modified it a bit. I don't completely understand how the joins work which is probably my problem. I'm also not completely sure if I can add up those counts...
Also, I'm more than a little confused with the fact that this similar query works fine:
$query_bars_num = "select b.*,
(count(t1.first_bar) + count(t2.second_bar) + count(t3.third_bar)) as 'bar_count'
from barlist b
left join userdestinations t1
on b.id = t1.first_bar and t1.date = '$date'
left join userdestinations t2
on b.id = t2.second_bar and t2.date = '$date'
left join userdestinations t3
on b.id = t3.third_bar and t3.date = '$date'
where b.city = '$hometown'
group by b.id
order by bar_count desc";
$bars_num = mysql_query($query_bars_num, $connBarHopper) or die(mysql_error());
$row_bars_num = mysql_fetch_assoc($bars_num);
Any help is appreciated