table个数据如何统计table个数据
How count table a data for every data of table a
我有三个tableA
,B
,C
.
A table:
id,name
B table:
id,a_id,date
C table:
id,b_id,type(value is 0/1)
我想通过计算 C 数据来打印所有 A.name、A.id 和 C.countingdata,其中 C.type=1 使用具有 A [的 B table =41=] id
结果如下所示:
A.id A.name C.countingdata
1 abc 4
2 vfd 2
3 fdg 0
您可以找到如下查询:
Select
A.id
,A.name
,COUNT(C.id)
FROM A
JOIN B ON A.id = B.a_id
JOIN C ON B.id = C.b_id ANd C.type = 1
GROUP BY
A.id
,A.name
好吧,您可以先内联 B
和 C
,执行 group by
并使用 count()
得到 C.countingdata
。此子查询的另一个连接 B
本身以容纳 a_id
在结果集中。
现在,您可以在 A
和上述子查询之间进行内部联接以获得结果。
SQL:
select A.id, A.name, derived.countingData
from A
inner join (
select B.id as b_id,B.a_id,sub_data.countingData
from B
inner join (
select B.id,count(B.id) as countingData
from B
inner join C
on B.id = C.b_id
where C.type=1
group by B.id
) sub_data
on B.id = sub_data.id
) derived
on A.id = derived.a_id
我有三个tableA
,B
,C
.
A table:
id,name
B table:
id,a_id,date
C table:
id,b_id,type(value is 0/1)
我想通过计算 C 数据来打印所有 A.name、A.id 和 C.countingdata,其中 C.type=1 使用具有 A [的 B table =41=] id
结果如下所示:
A.id A.name C.countingdata 1 abc 4 2 vfd 2 3 fdg 0
您可以找到如下查询:
Select
A.id
,A.name
,COUNT(C.id)
FROM A
JOIN B ON A.id = B.a_id
JOIN C ON B.id = C.b_id ANd C.type = 1
GROUP BY
A.id
,A.name
好吧,您可以先内联
B
和C
,执行group by
并使用count()
得到C.countingdata
。此子查询的另一个连接B
本身以容纳a_id
在结果集中。现在,您可以在
A
和上述子查询之间进行内部联接以获得结果。
SQL:
select A.id, A.name, derived.countingData
from A
inner join (
select B.id as b_id,B.a_id,sub_data.countingData
from B
inner join (
select B.id,count(B.id) as countingData
from B
inner join C
on B.id = C.b_id
where C.type=1
group by B.id
) sub_data
on B.id = sub_data.id
) derived
on A.id = derived.a_id