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
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.
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.