如何从子查询中的不同表中获取特定行的数量

时间:2010-01-26 22:21:18

标签: sql mysql subquery

我知道这是可能的,但我没有足够的经验知道如何做子查询 情况如下:

Table 1:
+--------------------+--------------------+
|               v_id |             v_name |
+--------------------+--------------------+
|                  1 |            v_name1 |
+--------------------+--------------------+
| etc...

Table 2:
+--------------------+--------------------+
|               a_id |             a_name |
+--------------------+--------------------+
|                  1 |            a_name1 |
+--------------------+--------------------+
| etc...

Table 3:
+--------------------+--------------------+
|               v_id |               a_id |
+--------------------+--------------------+
|                  1 |                  1 |
+--------------------+--------------------+
|                  1 |                  2 |
+--------------------+--------------------+
|                  1 |                  3 |
+--------------------+--------------------+
|                  2 |                  3 |
+--------------------+--------------------+
|                  2 |                  1 |
+--------------------+--------------------+

我认为这是一种非常普遍的情况 因此,我在Table 1Table 2中有唯一的条目 我想SELECT来自Table 1的所有行,并获取(作为每行中的最后一个单元格)Table 3中具有相应值的行数。

这不起作用:

SELECT t1.* , COUNT(SELECT t3.* FROM  `table_3` t3 WHERE t3.v_id = t1.v_id) as entries
FROM  `table 1` t1;

我确信我会被这里的专家告知,这是错的,但坦率地说,这就是我正在寻找的东西(以及一些有用的解决方案!)。 ;)

3 个答案:

答案 0 :(得分:4)

使用:

   SELECT t1.*,
          COALESCE(x.num_rows, 0) AS entries
     FROM `table 1` t1
LEFT JOIN (SELECT t3.v_id,
                  COUNT(*) 'num_rows'
             FROM `table_3` t3
         GROUP BY t3.v_id) x ON x.v_id = t1.v_id

答案 1 :(得分:3)

SELECT t1.* , (SELECT COUNT(*) FROM  `table_3` t3 WHERE t3.v_id = t1.v_id) as t3Count as entries 
FROM  `table 1` t1; 

答案 2 :(得分:2)

SELECT T1.v_id, COALESCE(COUNT(T3.v_id), 0)
FROM Table1 AS T1
LEFT JOIN Table3 AS T3
ON T1.v_id = T3.v_id
GROUP BY T1.v_id