2010-09-09 79 views
1

我最后的任务太模糊了,所以我会修改它。我知道以下是不正确的SQL语法,但是您应该能够获得我尝试执行的查询的要点。计数子查询

select id, 
     title, 
     count(select x 
       from otherTable 
      where otherTable.id = thisTable.id) as new_row 
from thisTable 

我希望这个更好解释一下。

+1

@Camony:如果在外表中没有匹配的行,那么你是否仍然想显示0作为计数?在这种情况下,内部连接不会工作,我认为... – 2010-09-09 03:55:15

回答

3
select tt.id, tt.title, count(ot.id) as count 
from thisTable tt 
inner join otherTable ot on ot.id = tt.id 
group by tt.id, tt.title 
+0

比冒犯更容易解决。 – 2010-09-09 02:53:40

+0

@Evan Carroll:Zee括号,zay do nuTH! :) +1 – 2010-09-09 02:59:43

+1

嘿家伙,我仍然可以触摸我自己的答案? )) – 2010-09-09 03:27:01

1

另一种解决方案。如果你想知道行数,而不是不同x值的数量,那么使用count(*)而不是count(distinct x)。

select id, title, 
    (select count(distinct x) from otherTable 
    where otherTable.id = thisTable.id) as new_row 
from thisTable