![](/img/trans.png)
[英]MySQL - How to transfer values from one table to another depending on criteria
[英]MYSQL - sum values of rows from one table based on criteria from another
我試圖找出正確的 SQL 查詢來執行以下操作:
我有 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 |
例如,我如何找出所有藍色物品的總成本? (應達到80)
如果全部放在一張表中,我可以這樣做: SELECT SUM(cost) FROM table1 WHERE colour='blue';
我將如何使用 2 個表來做到這一點?
提前致謝
對 id 列執行 JOIN 以連接兩個表。 然后根據顏色對項目進行求和。
-- 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。 當列名不重疊/沖突時,它們不是嚴格需要的。
如果需要項目計數,請包含 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';
您可以使用 where 子句和 IN 運算符來查找表 2 中存在 id 且顏色為藍色的表上特定產品的成本總和。 簡單地說,藍色產品 ID 應該在查詢 1 中找到:
SELECT table1.id from table1 where table1.colour = "blue";
總成本找到:
select sum(cost) from table2;
用 in 關鍵字加入:
select sum(cost) from table2 where table2.id in (SELECT table1.id from table1 where table1.colour = "blue")
in 運算符的工作方式類似於循環,並在 where 子句查詢中匹配已建立的 id。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.