HAVING COUNT接收其他COUNT值

时间:2016-11-26 15:45:12

标签: mysql join count group-by having

我正在使用两个不同的表中的select,它们应该与组引用ID匹配,例如: 表1和表2

+-----+-----+------------+   +-----+------+
| 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 |
                             +-----+------+

我需要从表2 中获取与{em>表1 上的组完全匹配的nid个值。在表1 中搜索的引用是tid。 我相信SQL会是这样的:

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;

但是如何才能准确地count替换硬编码的number 4

1 个答案:

答案 0 :(得分:0)

SELECT t2.nid
  FROM table1 t1
INNER JOIN
  table2 t2
  ON t1.gid = t2.gid;
WHERE t2.tid IN (731, 736, 746, 751)
  GROUP BY t2.gid