Jump to content

COUNT() IN A 3 TABLE JOIN


virtual_odin

Recommended Posts

I am trying to record separately views and clicks for a set of items.  I have started with three tables 1: the items; 2: the time of the view, reference by the id in table 1; and 3: the time of the click, also referenced by the id in table 1.

So I thought this would give me the answer, but it gives the same number of views and clicks.  Where have I gone wrong please?  I did wonder about a tale of views and click with a "type" field, but that doesn't feel as neat.

[code]
SELECT t1.*,
COUNT(t2.est_id) AS clicks,
COUNT(t3.est_id) AS impressions

FROM t1
LEFT JOIN t2 ON ( t1.id = t2.est_id )
LEFT JOIN t3 ON ( t1.id = t3.est_id )

GROUP BY t1.id
ORDER BY NULL
[/code]

As always, you assistance would be greatly appreciated.
Link to comment
https://forums.phpfreaks.com/topic/35212-count-in-a-3-table-join/
Share on other sites

This now works.  Thanks for your help fenway.

[code]
$query1 = "SELECT
t1.*,
COUNT(t3.est_id) AS clicks
FROM t1
LEFT JOIN t3 ON ( t1.id = t3.est_id )
GROUP BY t1.id
ORDER BY NULL";

$query2 = "SELECT
COUNT(t2.est_id) AS impressions
FROM t1
LEFT JOIN t2 ON ( t1.id = t2.est_id )
GROUP BY t1.id
ORDER BY NULL";

$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
$numresults = mysql_num_rows($result1);
for ($i=0; $i <$numresults; $i++) {
$row1 = mysql_fetch_assoc($result1);
$row2 = mysql_fetch_assoc($result2);
$row1['impressions'] = $row2['impressions'];
// etc
}
[/code]

I did it this way to end up with a single array to work with for the next part of the script.
I have ran into the very same problem. what would be the subquery sollution, as i cannot split my query into two separate queries.
I have described my similar problem here : [url=http://www.phpfreaks.com/forums/index.php/topic,124850.0.html]http://www.phpfreaks.com/forums/index.php/topic,124850.0.html[/url]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.