HAVING COUNT receiving other COUNT value
<p>I'm working with a select in two different tables that should be match by group reference id, like:
<em>Table 1 and table 2</em>:</p>

<pre><code>+-----+-----+------------+   +-----+------+
| gid | tid | created    |   | gid | nid  |
+-----+-----+------------+   +-----+------+
|   0 | 816 | 1480002041 |   |   0 | 1123 |
|   1 | 731 | 1480003932 |   |   0 | 1124 |
|   1 | 736 | 1480003932 |   |   1 | 1125 |
|   2 | 746 | 1480003932 |   |   1 | 1126 |
+-----+-----+------------+   |   1 | 1123 |
                             |   2 | 1124 |
                             |   1 | 1129 |
                             +-----+------+
</code></pre>

<p>I need to get <code>nid</code> values from <em>table 2</em> that have a exactly group match with the group on <em>table 1</em>. The reference to search in <em>table 1</em> is <code>tid</code>.
I believe that the SQL would be something like that:</p>

<pre><code>SELECT  t1.nid
FROM table1 t1
INNER JOIN
(
    SELECT  gid 
    FROM    table2 
    WHERE   tid IN (731, 736, 746, 751)
    GROUP   BY gid
    HAVING  COUNT(DISTINCT tid) = 4
) t2 ON t1.gid = t2.gid;
</code></pre>

<p>But how can I get the exactly <code>count</code> to replace hard coded <code>number 4</code>?</p>