簡體   English   中英

在多個表之間使用計數和聯接

[英]using count and joins across multiple tables

示例:表1:

id   name

1    sim
2    sam
3    jas

表2

key   age
1     10
1     20
2     40
3     10

表3:

id    rating
2       7
2       6
3       8
3       7
1       9

現在,我需要的是

在兩個表即表A和表B中使用group by分組的行數。

select t1.id, count(t2.key) as a, count(t3.id) as b
FROM 
table1 t1
LEFT JOIN 
table2 t2
ON 
t1.id = t2.key
LEFT JOIN 
table3 t3
ON 
t1.id = t3.id
GROUP BY t1.key, t2.id

結果我期望:

id   a  b
1    2  1
2    1  2
3    1  2

由於在所有3個表之間創建叉積,因此得到重復項。 使用COUNT(DISTINCT)篩選出重復項。

select t1.id, count(DISTINCT t2.age) as a, count(DISTINCT t3.rating) as b
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.key
LEFT JOIN table3 t3 ON t1.id = t3.id
GROUP BY t1.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM