表A有许多行,其中只有一些在表B中有(多个)子项。我需要计算表A中有子项的行。
目前我有
SELECT count(tableA.id) as count
FROM (tableA)
JOIN tableB ON tableB.tableA_id = tableA.id
不幸的是,这也会计算来自tableB的多个孩子。有什么方法可以阻止这种情况吗?
答案 0 :(得分:2)
这应该有效:
SELECT count(tableA.id) as count
FROM (tableA)
where id in (select tableA_id from tableB)
或者,使用EXISTS:
SELECT count(tableA.id) as count
FROM (tableA)
where exists (select 1 from tableB where tableB.tableA_id = tableA.id)
答案 1 :(得分:1)
您只需要将DISTINCT关键字放入COUNT(内部联接仅包含tableA中具有tableB中子项的行)
SELECT COUNT(DISTINCT tableA.id) AS count
FROM (tableA)
JOIN tableB ON tableB.tableA_id = tableA.id
答案 2 :(得分:0)
有两种选择:
SELECT count(distinct tableA.id) as `count`
FROM tableA
JOIN tableB ON tableB.tableA_id = tableA.id
或:
SELECT count(*) as `count`
FROM (tableA)
where exists
(select null from tableB where tableB.tableA_id = tableA.id)