您将需要使用DISTINCT
,但您还需要计算 ID,而不是外键:
SELECT
table1.name,
COUNT(DISTINCT table2.id) AS table2_count,
COUNT(DISTINCT table3.id) AS table3_count,
COUNT(DISTINCT table4.id) AS table4_count,
SUM(table4.size) AS table4_size
FROM table1
LEFT JOIN table2 ON table1.id = table2.table1_id
LEFT JOIN table3 ON table2.id = table3.table2_id
LEFT JOIN table4 ON table3.id = table4.table3_id
WHERE table1.id = 1
这里有一个fiddle.
解释: The DISTINCT
关键字消除所有重复值,从而生成唯一值列表。
如果您运行查询时没有COUNT()
and SUM()
, 你得到:
name table1_id table2_id table3_id size
test 1 1 1 1024
test 1 1 1 200
test 1 (null) (null) (null)
test 1 (null) (null) (null)
所以如果你添加COUNT()
and SUM()
,你显然得到:
name table1_id table2_id table3_id size
test 4 2 2 1224
然而,使用DISTINCT
与您的查询没有帮助,因为您可以清楚地看到重复的值,这将导致:
name table1_id table2_id table3_id size
test 1 1 1 1224
现在,如果您运行我的查询而不使用COUNT()
and SUM()
, 你得到:
name table1_id table2_id table3_id size
test 1 1 1 1024
test 1 1 2 200
test 2 (null) (null) (null)
test 3 (null) (null) (null)
如果您添加COUNT()
and SUM()
,您会得到与查询完全相同的结果:
name table1_id table2_id table3_id size
test 4 2 2 1224
但是,因为这次您有不同的值(即并非全部都是 1),所以现在如果您使用DISTINCT
, 你得到:
name table1_id table2_id table3_id size
test 3 1 2 1224