MySQL Left Join - 如何获取第二个表中找到的记录数

时间:2013-06-19 06:42:44

标签: mysql

Table1

id    Name

1     John

2     Sheldon

3     Sarah

======

Table2

rid   id  id2  relation

1     1    2    1

2     1    3    1

如何在一个查询中获取表1中的所有成员以及每个成员的总关系。

我想要的结果应该是:

Jhon       2

Sheldon    0

Sarah      0

2 个答案:

答案 0 :(得分:3)

select Table1.name, count(Table2.id) from Table1 LEFT Join Table2 on Table1.id=Table2.id group by Table2.id

    OR 

select Table1.name,IFNULL(count(Table2.id), 0) from Table1  LEFT Join Table2  on Table1.id=Table2.id group by Table2.id

enter image description here

答案 1 :(得分:1)

SELECT t1.name, IFNULL(COUNT(t2.id2), 0)
FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t2.id
GROUP BY t1.id