SQL insert/update 根据某些条件从另一个 table 到 table

SQL insert/update to a table from another table based on some condition

我有一个如下所示的 table 名为 table1:

+-----------+-------+
| productid | stock |
+-----------+-------+
|         1 |    10 |
|         2 |    20 |
|         3 |    30 |
+-----------+-------+

我需要从另一个名为 table2:

的 table 插入/更新上面的 table
+-----+-------+
| PId | stock |
+-----+-------+
|   1 |    20 |
|   2 |    40 |
|   4 |    10 |
+-----+-------+

我想执行具有以下条件的 SQL 查询:

  1. 如果 table2 中的 PId 存在于 table1 中的 Productid 中,则需要更新库存值。
  2. 如果来自 table2 的 PId 不存在于 table1 的 Productid 中,则需要将库存值作为新行插入 table1 来自 table 2.

所以在 table1 中执行查询输出后将如下所示:

+-----------+-------+
| productid | stock |
+-----------+-------+
|         1 |    20 |
|         2 |    40 |
|         3 |    30 |
|         4 |    10 |
+-----------+-------+

帮助我获得查询,因为我是 SQL 的新手。提前致谢!

您需要 MERGE 语句。现在大多数数据库管理系统都支持它:

MERGE INTO table1
USING table2
   ON table1.productid=table2.pid
WHEN MATCHED THEN UPDATE SET
  stock = table2.stock
WHEN NOT MATCHED THEN INSERT VALUES (
  table2.pid
, table2.stock
)
;

SELECT * FROM table1 ORDER BY 1;
-- out  OUTPUT 
-- out --------
-- out       3
-- out (1 row)
-- out 
-- out Time: First fetch (1 row): 27.090 ms. All rows formatted: 27.155 ms
-- out  productid | stock 
-- out -----------+-------
-- out          1 |    20
-- out          2 |    40
-- out          3 |    30
-- out          4 |    10