简体   繁体   English

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

[英]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.

相关问题 从一个表中选择,从另一个表中计数 - Select from one table and count from another 从一个表中选择,并从同一查询中的另一个表计数 - Select from one table, and count from another table in same query MySQL SELECT COUNT从一个表和ID从另一个表? - MySQL SELECT COUNT from one table and ID from another? 如何选择一个表中存在ID的行,而另一表中没有ID? - How to select rows where the ID exists in one table, but not another? 计算具有一个值的行数和具有另一个值的行数,并输出表中出现的最低值 - Count number of rows with one value and rows with another value, and output lowest appearing value in table 从一个表中选择结果,并为每一行从另一张表中选择具有相同ID的所有行 - Select results from one table and for each row select all rows that have the same id from another table 从一个表中选择所有行,并为另一表中的每一行选择一个特定值 - Select all rows from one table and one specific value for each row from another table 计算一个表中的家庭成员数,用于另一张名为 house 的表中的每一行? - Count number of family members from one table for each rows in another table called house? 如何在另一个表中选择具有匹配行的行 - How to select rows with matching rows in another table 从一个表中选择计数,另一个表中有一个位置 - Select count from a table with a Where on another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM