社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

MYSQL——基于另一个表的条件,对一个表中的行进行求和

cato66 • 4 年前 • 1850 次点击  

我试图找到正确的SQL查询来执行以下操作:

我有两个表,希望根据从另一个表中选择的条件计算其中一个表中的行的总和。

table1
| id  | colour      | item
| ------------------| ----------|
| 1   | blue        | anorak
| 2   | blue        | jeans
| 3   | green       | t-shirt
| 4   | yellow      | t-shirt


table2
| id  | cost     |
| ---------------|
| 1   | 58       |
| 2   | 22       |
| 3   | 36       |
| 4   | 19       |

例如,我如何计算所有蓝色物品的总成本?(总数应为80)

如果全部放在一张桌子上,我可以做: 从表1中选择金额(成本),其中color='blue';

我该如何处理这两张桌子?

提前谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130677
文章 [ 3 ]  |  最新文章 4 年前
Dan Sorensen
Reply   •   1 楼
Dan Sorensen    5 年前

对id列执行联接以连接两个表。然后根据颜色对项目求和。

-- Find the total cost where item colour is blue.
SELECT SUM(t2.cost) AS TotalCost
FROM Table2 t2
JOIN Table1 t1 ON t2.id = t1.id
WHERE t1.colour = 'blue';

注:为了清晰起见,我使用了表别名t1和t2。当列名不重叠/冲突时,不严格需要它们。

如果需要item count,可以使用MySQL函数count()来查找集合中匹配的行数。

-- Find the number of items & total cost where item colour is blue.
SELECT 
  COUNT(*) AS BlueItemCount,
  SUM(t2.cost) AS CostOfBlueItems
FROM Table2 t2
JOIN Table1 t1 ON t2.id = t1.id
WHERE t1.colour = 'blue';
Yakup Beyoglu
Reply   •   2 楼
Yakup Beyoglu    5 年前

您可以使用where子句和IN运算符来查找表2中id为且颜色为蓝色的特定产品的成本总和。 简单地说,蓝色的产品ID应该在查询1中找到:

SELECT table1.id from table1 where table1.colour = "blue";

成本加总:

 select sum(cost) from table2;

加入关键字:

select sum(cost) from table2 where table2.id in (SELECT table1.id from table1 where table1.colour = "blue")

in运算符的工作方式类似于where子句查询中的循环和匹配id。

nbk
Reply   •   3 楼
nbk    5 年前

这是一样的,你需要 join 桌子

SELECT SUM(cost) FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id WHERE colour='blue';
| SUM(cost) |
| --------: |
|        80 |

db<>不停摆弄 here