选择一个表的一部分并计算另一个表的行

时间:2012-05-04 18:24:04

标签: php mysql

我有2个MySQL表:人和&连接

我想从人员中选择所有列,并计算他们在连接表中的连接数。

--------------------   ----------------------
| People           |   | Connections        |
--------------------   ----------------------
| person_id | name |   | cnt_id | person_id |
--------------------   ----------------------

我想从所有人中选择所有人,并选择该人的person_id出现在第二个表中的次数。

我一直想弄明白,但不能。希望你们都能提供帮助。

谢谢!

2 个答案:

答案 0 :(得分:2)

如果有人没有连接,这将给出一个零计数的行:

SELECT
    People.person_id,
    People.name,
    COUNT(Connections.person_id) AS number_of_connections
FROM People
LEFT JOIN Connections
ON People.person_id = Connections.person_id 
GROUP BY People.person_id

答案 1 :(得分:1)

试试这个

SELECT name,count(Connection.person_id) as cnt FROM 
      People LEFT JOIN Connection ON People.person_id = Connection.person_id 
      GROUP BY Connection.person_id