1

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

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

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

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

我一直想弄清楚,但做不到。希望大家能帮忙。

谢谢!

4

2 回答 2

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
于 2012-05-04T18:30:40.437 回答
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
于 2012-05-04T18:27:34.743 回答