Note that there are some explanatory texts on larger screens.

plurals
  1. POMySql correlated subquery count across tables
    primarykey
    data
    text
    <p>I have 3 tables that are related with the fields below:</p> <pre><code>forums topics posts f_id ---- f_id t_id ---- t_id p_id </code></pre> <p>For a given <code>f_id</code> I'm trying to 2 different counts in 1 query:</p> <ol> <li>the total numbers of <code>t_id</code> (topics) </li> <li>the total numbers of <code>p_id</code> (posts)</li> </ol> <p>for example <code>f_id=78</code> should simply result to</p> <pre><code>tc | pc --------- 4 | 3 </code></pre> <p>Meaning there are 4 topics and a total of 3 post to those topics, all in that forum. But when I use this simple query (which is after hours of trying and research my best attempt):</p> <pre><code>SELECT ( SELECT COUNT( t_id ) FROM topics WHERE f_id = '78' ) AS tc, ( SELECT COUNT( p_id ) FROM posts WHERE posts.t_id = topics.t_id ) AS pc FROM topics WHERE topics.f_id = '78' </code></pre> <p>But this only results to a count for each row in topics that matches the <code>f_id</code> like this:</p> <pre><code>tc | pc --------- 4 | 0 4 | 1 4 | 2 4 | 0 </code></pre> <p>and not a total count. I'm genuinely stuck here, even though I was pretty sure this was not a hard thing to achieve. Thanks!</p> <hr> <h2>Edit: as requested a bit of sample data:</h2> <p><strong>forums</strong></p> <pre><code>f_id t_name ... --------------------- 78 Test ... 33 Something ... </code></pre> <p><strong>topics</strong></p> <pre><code>f_id t_id t_date ... ---------------------------- 78 28 2011-07-14 ... 78 53 2011-07-14 ... 78 54 2011-07-14 ... 78 56 2011-07-14 ... 33 57 2011-07-14 ... </code></pre> <p><strong>posts</strong></p> <pre><code>t_id p_id p_date ... --------------------------- 54 2 2011-07-14 ... 54 4 2011-07-14 ... 53 5 2011-07-14 ... </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload