[英]Select parts of one table and count rows of another
I have 2 MySQL tables: people & connections 我有2个MySQL表:人和连接
I want to select all columns from people and also count up how many connections they have in the connections table. 我想从人员中选择所有列,并计算他们在连接表中有多少连接。
-------------------- ----------------------
| People | | Connections |
-------------------- ----------------------
| person_id | name | | cnt_id | person_id |
-------------------- ----------------------
I want to select all from people and select a count of how many times the person_id for that person appears in the second table. 我想从人员中选择所有人,并选择该人的person_id在第二个表中出现的次数。
I have been trying to figure it out, but can't. 我一直想弄明白,但不能。 Hopefully you all can help. 希望你们都能提供帮助。
Thanks! 谢谢!
If there is a person with no connections, this will give a row with zero count: 如果有人没有连接,这将给出一个零计数的行:
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
try this 尝试这个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.