如何计算 SQLite 中某个 table 中外来 table id 的出现次数?

How to count occurrences of a foreign table id in a certain table in SQLite?

所以我有以下 table:

Table A
a_id    b_id

Table B
b_id    b_name

我想计算 table B 中的 id 在 Table A 中的 b_id 列中显示或用作值的次数。据推测,结果应该是这样的:

ID     count     name
1      10        aaaa
2      8         bbbb
3      11        cccc

我考虑过使用以下查询:

Select b_id from table_b 

获取所有ID。然后遍历每一个并像这样计算它们:

Select count(*) from table_a where b_id = ''

但是这个过程太长了。我想在一个查询中将其缩短一点。但我不知道如何使用 SQLite 语言遍历每一行。

(即使只是向正确的方向推动也会有所帮助。)

以下 sql 查询应该有效:

   SELECT      a.a_id, 
               COUNT(b.b_id)    
   FROM        Table_A a
   JOIN  Table_B b on a.b_id=b.b_id
   GROUP BY    a.a_id

以上有效:

这是你的要求吗?

这可以通过 correlated subquery:

SELECT b_id AS ID,
       (SELECT COUNT(*)
        FROM TableA
        WHERE TableA.b_id = TableB.b_id
       ) AS count,
       b_name AS name
FROM TableB;