繁体   English   中英

mysql 使用聚合连接两个表

[英]mysql join two tables with aggregations

我正在尝试根据id连接两个表并在最终结果中进行聚合。

Table1

id name val
0  A    10
1  B    20
2  C    10

Table2

id cat price
0  1   10
0  2   20
1  1   10
1  2   10
2  1   10


SELECT t1.*, t2. FROM 
Table1 t1
JOIN Table2 t2 ON t1.id = t2.id;

我想加入这两个表,并在最终结果中聚合Table2中的匹配行。 聚合 function 是Average 最后结果:

id name val price
0  A    10  15
1  B    20  10
2  C    10  10

使用聚合函数时,必须使用 GROUP BY 子句来通知 DBMS 根据哪些属性进行聚合。 以指示您使用的聚合的方式命名结果也是一种很好的做法。

SELECT t1.id, t1.name, t1.val, avg(t2.price) as avg_price
FROM Table1 t1
JOIN Table2 t2 on t2.id = t1.id
GROUP BY t1.id, t1.name, t1.val
select t1.id, t1.name, t1.val, avg(t2.price) as price from Table1 as t1 join Table2 as t2 on t1.id = t2.id group by t1.id, t1.name, t1.val

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM