选择 count(*) 作为较大选择查询的一部分

秃鹰51

我正在使用两个查询:

select * from ControlPoints where LineGroup = 123001
select count(*) from BitAssignments where LineGroup = 123001

以确定是否需要更新 BitAssignments 表。我可以以某种方式组合这两个查询吗?

这两个表是从外部源填充的,其想法是 1) 查看是否缺少 ControlPoints 的任何成员,以及 2) 如果它们存在,查看是否所有 BitAssignments 都在表中。

架构如下:

ControlPoints table
   LineGroup     int (primary key)
   Name          string
   NumControls   int
   NumInd        int

BitAssignments table
   LineGroup     int
   BitPosition   int
   Mnemonic      string

对于给定的 ControlPoint,ControlPoints 表中将只有一条记录,但 BitAssignments 表中可能有数百行 Bit 数据。

我需要一个查询来告诉我是否已添加(或删除)外部数据中的新控制点,或者是否已从外部数据中添加/删除了对现有控制点的新位分配。另一种方法是从头开始重建两个表,但此过程需要 12 多个小时才能完成(BitAssignments 中大约有 300,000 条记录)。

类似的东西:

select a.LineGroup b.select count(Mnemonic) from ControlPoints a, BitAssignments b where a.LineGroup=123001 

当然,这不起作用。

用户170442

你需要做两个步骤:

  1. JOIN 表

  2. 添加 GROUP BY 子句,因为您使用的是 COUNT 聚合函数

在这两个步骤之后,您的查询将如下所示:

SELECT cp.LineGroup, cp.Name, cp.NumControls, cp.NumInd, COUNT(ba.Mnemonic) BitAssignmentsCnt
FROM ControlPoints cp LEFT JOIN BitAssignments ba ON cp.LineGroup=ba.LineGroup
GROUP BY cp.LineGroup, cp.Name, cp.NumControls, cp.NumInd, ba.LineGroup

如果您想显示所有控制点,无论它们是否有任何 BitAssignments,您都可以使用LEFT JOIN如果您对 BitAssignmentsCnt=0 不感兴趣,您可以使用INNER JOIN而不是 LEFT JOIN。

GROUP BY需要指定您在查询中使用的所有列(在 select 或 JOIN 中)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章