简体   繁体   English

SQL表-根据table1值对table2中的行进行计数

[英]SQL tables - counting rows in table2 based on table1 values


I have two MySQL tables with the same column names: 我有两个具有相同列名的MySQL表:

table1 = id, company table1 = ID,公司

table2 = id, company table2 = ID,公司

I want to add one column to table1 with the count of lines in table2 containing the same id and company. 我想在table1中添加一列,其中table2中的行数包含相同的ID和公司。

For example: 例如:

table1
id, company
1, 12
2, 12
3, 14
4, 14

table2
id, company
1, 4
1, 5
1, 12
1, 12
3, 14

I wish to obtain: 我希望获得:

table1
id, company, table2count
1, 12, 2
2, 12, 0
3, 14, 1
4, 14, 0

For some reasons the query proposed below returns a count = 1 even if no match is found. 由于某些原因,即使未找到匹配项,下面提出的查询也会返回count = 1。 I have been testing in R using the sqldf library: 我一直在使用sqldf库在R中进行测试:

> table1
           id company
1  2187163455    3509
2  1762086305    5824
3  1762086305    9909
4   457591705    9909
5   456203419    9909
6  1877752457    9909
7   442780095    9909
8   471442042    9909
9   457590444    9909
10 3879669310    9909
> table2
            id company
 1:      86246    9909
 2:      86246    5824
 3:  442780095    7205
 4:      86246    5558
 5: 1762086305    5824
 6:      86246    9909
 7: 1762086305    9909
 8:      86246    3509
 9:      86246    3509
10:      86246    3504
> sql_query = " SELECT table1.id, table1.company, COUNT(*) AS table2count
+ FROM table1
+ LEFT JOIN table2 ON table1.id=table2.id AND table1.company = table2.company
+ GROUP BY table1.id"
> sqldf(sql_query)
          id company table2count
1  442780095    9909           1
2  456203419    9909           1
3  457590444    9909           1
4  457591705    9909           1
5  471442042    9909           1
6 1762086305    9909           2
7 1877752457    9909           1
8 2187163455    3509           1
9 3879669310    9909           1

It is a good question, I can't understand the downvoter. 这是一个好问题,我听不懂下降投票的人。

What we do: 我们所做的:

  • First we create a JOIN-ed table between table1 and table2 首先,我们在table1和table2之间创建一个JOIN-ed表
  • Second we use a "group by" query to calculate the link counts. 其次,我们使用“分组依据”查询来计算链接数。

I assumed you have a linking table as table2, thus the "id" column isn't a unique in it (but it is in table1). 我假设您有一个链接表为table2,因此“ id”列在其中不是唯一的(但它在table1中)。

SELECT table1.id, table1.company, COUNT(*) AS table2count
FROM table1
LEFT JOIN table2 ON table1.id=table2.id AND table1.company = table2.company
GROUP BY table1.id

In other SQL-servers we couldn't SELECT for "table1.company", because it isn't an aggregate column. 在其他SQL服务器中,我们无法选择“ table1.company”,因为它不是聚合列。 Only mysql has this feature. 只有mysql具有此功能。

SELECT table1.id, table1.company, COUNT(  table2.id  ) AS table2count
FROM table1
LEFT JOIN table2 ON table1.id=table2.id and table1.company = table2.company
GROUP BY table1.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM