Join

選擇在加入時使用與 id 不同的值

  • March 31, 2017

我有兩個表,標準化:

table1
id    quality    product_id 
1     100       1
2     100       2
3     10        4
4     50        2

table2
product_id    product    material
1             tinder     metal
2             gold       metal
3             timber     wood
4             stone      rock

如何獲得第一張桌子上的所有金屬物品?我試過了

select sum(quality) from table1 join table2 on table2.material = 'metal';

但似乎不正確(720),應該是250。

我不確定我是否理解表格之間的關係,但如果我這樣做應該可以:

SELECT 
   SUM(quality) 
FROM table1 
WHERE product_id IN (
   SELECT 
       product_id 
   FROM table2 
   WHERE material = 'metal'
   )

你可以用一個簡單的JOIN

SELECT
   SUM(table1.quality) as qlty,
   GROUP_CONCAT(table1.product_id ORDER BY table1.product_id ASC) AS all_products_id_matching
FROM test.table1
JOIN test.table2 ON (table2.product_id=table1.product_id)
WHERE table2.material='metal';

或子查詢:

SELECT
   SUM(table1.quality) as qlty
FROM test.table1
WHERE table1.product_id IN (SELECT table2.product_id 
                           FROM test.table2 
                           WHERE table2.material='metal');

您也可以JOINUSING( product_id) 或一起使用WHERE EXISTS

引用自:https://dba.stackexchange.com/questions/108421