2009-11-10 65 views
0

我想连接两个表,并根据第一个表中的ID获取数据,并根据相同的ID计数第二个表中的列记录。我想要一个单一的查询给我的输出。SQL加入并计数

+1

请在这里问问题时加倍努力。示例代码。更多细节。拼写。语法。 – bguiz 2009-11-10 06:40:44

+1

你能举两个表中的日期和你想要的输出的例子吗? – beggs 2009-11-10 06:40:51

+0

,请给它一个有意义的名称 – phunehehe 2009-11-10 06:41:34

回答

3

认为你问这样的查询:

select t1.id, count(t2.id) 
from table1 as t1 
left outer join table2 as t2 
    on t2.table1_id = t1.id 
group by t1.id; 
1
select 
    ID, 
    (select count(*) from table2 where ID=p.ID) as [count] 
from table1 p 
4

以下是为您的问题和提出的解决方案用例/例子: 你有两个表用户和分别存储用户数据和联系信息的User_Friends。

而且您希望显示用户具有的联系人的姓名和数量。

Table User: 
id Name 
0 A 
1 B 
2 C 
3 D 

Table User_Friends: 
id friend_id 
0 1 
0 2 
0 3 
1 2 
1 3 

Output: 
Name Count(*) 
A  3 
B  2 
C  0 
D  0 

//Display the Name, number of friends 
SELECT Name, count(*) 
FROM User, User_Friends 
WHERE User.id = User_Friends.id 
GROUP BY User_Friends.id