[英]MYSQL - sum values of rows from one table based on criteria from another
I am trying to find out the correct SQL query to carry out the following:我试图找出正确的 SQL 查询来执行以下操作:
I have 2 tables and want to count total sum values of rows from one of them based on criteria selected from the other.我有 2 个表,想根据从另一个表中选择的标准计算其中一个的行的总和。
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 |
So for example how do I find out total cost of all blue items?例如,我如何找出所有蓝色物品的总成本? (Should amount to 80) (应达到80)
If it were all in one table I could do: SELECT SUM(cost) FROM table1 WHERE colour='blue';如果全部放在一张表中,我可以这样做: SELECT SUM(cost) FROM table1 WHERE colour='blue';
How would I do this with the 2 tables?我将如何使用 2 个表来做到这一点?
thanks in advance提前致谢
Perform a JOIN on the id column to connect the two tables.对 id 列执行 JOIN 以连接两个表。 Then SUM items based on color.然后根据颜色对项目进行求和。
-- 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';
Note: I used table aliases t1 and t2 for clarity.注意:为了清楚起见,我使用了表别名 t1 和 t2。 They are not strictly needed when column names do not overlap/conflict.当列名不重叠/冲突时,它们不是严格需要的。
If item count is needed, include the MySQL function COUNT() to find the number of matching rows in the set.如果需要项目计数,请包含 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';
you can use where clause and IN operator to find sum of cost of specific product on table which has id exist on the table 2 and colour is blue.您可以使用 where 子句和 IN 运算符来查找表 2 中存在 id 且颜色为蓝色的表上特定产品的成本总和。 simply, blue colors product ids should be find in query 1 with :简单地说,蓝色产品 ID 应该在查询 1 中找到:
SELECT table1.id from table1 where table1.colour = "blue";
sum of cost find with :总成本找到:
select sum(cost) from table2;
Join with in keyword :用 in 关键字加入:
select sum(cost) from table2 where table2.id in (SELECT table1.id from table1 where table1.colour = "blue")
in operator works like a loop and match founded id in where clause query. in 运算符的工作方式类似于循环,并在 where 子句查询中匹配已建立的 id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.