Mysql 如何根据不同的属性对所有股票求和

Mysql 如何根据不同的属性对所有股票求和,mysql,Mysql,我想显示属性,并用DISTINCT对每个属性的所有股票求和。 像 这是我的桌子 +----------+----------+ | attrid |attribute | +----------+----------+ | 1 | Blue | | 2 | Blue | | 3 | Red | | 4 | Red | +----------+----------+ 这是我的桌子 +---------

我想显示属性,并用DISTINCT对每个属性的所有股票求和。 像

这是我的桌子

+----------+----------+
| attrid   |attribute |
+----------+----------+
|        1 |    Blue  |
|        2 |    Blue  |
|        3 |    Red   |
|        4 |    Red   |
+----------+----------+
这是我的桌子

+----------+----------+
|   stock  | attrid   |
+----------+----------+
|     40   |    1     |
|     21   |    2     |
|     45   |    3     |
|     74   |    4     |
+----------+----------+

连接这两个表,对stock列求和,并按如下所示的属性ID进行分组

select sum(B.stock), A.attribute
from table1 A 
inner join table2 B on (A.attrid = B.attrid)
group by A.attribute

可能不必使用
DISTINCT
try
groupby

演示:

选择SUM(t2.stock)作为SUM\u stock,t1.attribute
来自表1 t1
加入表2 t2
在t1.attrid=t2.attrid上
按t1.1属性分组
select sum(B.stock), A.attribute
from table1 A 
inner join table2 B on (A.attrid = B.attrid)
group by A.attribute