【问题标题】:SQL query to insert/update the qty depending on the condition(unable to insert)根据条件插入/更新数量的 SQL 查询(无法插入)
【发布时间】:2015-11-23 21:36:33
【问题描述】:

我有一张像 Item 一样的桌子

ItemID ItemName 
1        a          
2        b

组件表

cid  name   rate
12    ff      2
13    tt      4
14    ff      4
15    ff      2

compenent_item

pk_id    cid    itemid    qty
1         12     1          3
2         13     1         4
3         14     1         4
4         15     1         4
5         12     2          3
6         13     2         4
7         14     2         4
8         15     2         4

如果我的组件表中不存在 itemid 和 cid,我必须在我的 component_item 表中插入。

我无法做出正确的查询

【问题讨论】:

  • 另外,标记您正在使用的 DBMS。
  • 你的语言有点含糊。如果 component_item 中没有行,这是否意味着您要在其中插入“Item”和“Component”的叉积? (在您的示例中为 8 行)?随着组件和项目的增长,这可能会使未来的更新成本非常高。
  • 寻找 MERGE 命令。

标签: sql database sql-insert


【解决方案1】:

除了我不知道你想要 qty 的值是多少...

Insert compenent_item(cid, itemId, qty)
Select i.ItemId, c.cid, ??
from Item I 
   full join component c
where not exists(Select * from compenent_item
                 where cid = c.cid
                    and itemId = i.ItemID)

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多