简体   繁体   English

来自两个不同表的COUNT个

[英]COUNT from two different tables

This is a funky question, I know this. 这是一个时髦的问题,我知道这一点。 And maybe it's all because I'm really tired. 也许这是因为我真的很累。

Now, don't blame the design - it is flawed, but nothing I can do anything about, ok? 现在,不要责怪设计-它有缺陷,但是我无能为力,好吗?

  • Two tables, linked by a id-field. 由ID字段链接的两个表。
  • First table contains positions in a warehouse (table P) 第一个表包含仓库中的职位(表P)
  • Second table contains articles stored on each position in the warehouse (table PA) 第二个表包含存储在仓库中每个位置的物品(表PA)
  • ALL positions in the warehouse are present in the P-table (> 5000 records) 仓库中的所有职位都在P表中(> 5000条记录)
  • Each position could contain more than one article 每个职位可能包含不止一篇文章
  • The are positions in the P-table not present in the PA-table P表中的位置是PA表中不存在的位置

The count from positionarticles PLUS the positions not present in positionarticles. 来自位置文章的计数加上位置文章中存在的位置。

Is there really no better way than this utter stupidity?: 真的没有比这完全愚蠢更好的方法了吗:

SELECT SUM(row)
FROM
(
  SELECT COUNT(*) row
  FROM PA
  UNION
  SELECT COUNT(*)
  FROM P
  WHERE ID NOT IN
    (
      SELECT P_ID
      FROM PA
    )
) as rowcounter

Sample data 样本数据

Table P: 表P:

ID   Name
1    A01
2    A03
3    B01  *
4    B02  *

Table PA: 表PA:

ID   P_ID   A_ID
1    1      201  *
2    1      202  *
3    1      203  *
4    2      205  *

And the count returned is 6 => 4 rows from PA + 2 rows (P_IDs not present in PA). 返回的计数为6 => PA的4行+ 2行(PA中不存在P_ID)。 Rows counted are star-marked (*). 计数的行带有星号(*)。

Try this: 尝试这个:

SELECT P.ID, COUNT(PA.ID) noOfArticles
FROM P 
LEFT JOIN PA ON P.ID = PA.P_ID 
GROUP BY P.ID

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

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