【问题标题】:Insert records in table based on 'master' record in same table根据同一表中的“主”记录在表中插入记录
【发布时间】:2012-03-20 13:30:37
【问题描述】:

我有一张桌子,例如pricerules,按商品为客户存储特价。现在我想根据其他用户同步价格规则。假设我有这个作为数据集:

+---------------------------+
| user_id | prod_id | price |
+---------+---------+-------+
| 10      | 1       | 1     |
| 10      | 2       | 5     |
| 10      | 3       | 7     |
| 20      | 2       | 5     |
| 30      | 2       | 5     |
| 30      | 3       | 7     |
+---------+---------+-------+

现在我想根据用户 10 的价格更新/插入其他几个用户的价格。我已经编写了删除和更新查询,但我坚持使用插入查询来插入新规则其他用户还没有。

如此有效地执行以下插入:

INSERT INTO pricerules 
(user_id, prod_id, price) 
VALUES 
(20, 1, 1), 
(20, 3, 7), 
(30, 1, 1);

有没有办法在一个查询中做到这一点?我一直在寻找 MINUS 来选择用户 20 不存在的记录,但我必须为每个用户执行一个查询。

我想也许我可以使用MERGE

我正在使用 Oracle 10.1 ..

【问题讨论】:

    标签: sql oracle merge


    【解决方案1】:

    你是对的。合并是要走的路。请尝试以下方法。

    merge into pricerules p
    using ( select t1.user_id, t2.prod_id, t2.price
       from 
       (select distinct user_id
       from pricerules
       where user_id <> 10) t1,
       (select distinct prod_id, price
       from pricerules
       where user_id = 10) t2
       ) t
    on (p.user_id = t.user_id
       and p.prod_id = t.prod_id
       and p.price = t.price)
    when not matched then 
       insert (user_id, prod_id, price) values (t.user_id, t.prod_id, t.price) ;
    

    【讨论】:

    • OP 要求它是based upon the prices of user 10,所以也许你需要添加到 subqry t1 where user_id&lt;&gt;10 和 subqry t2 where user_id=10
    • 不幸的是,当您还需要使用序列(使用 seq.nextval)插入主键时,这种方法似乎效果不佳。序列将始终增加 +1。
    • 序列填充了哪个字段?
    【解决方案2】:

    我好久没用Oracle了,所以我的语法可能有点不对,但大体思路是:

    INSERT INTO pricerules 
    (user_id, prod_id, price) 
    select 20 as user_id, 1 as prod_id, 1 as price from dual
    union all
    select 20, 3, 7 from dual
    union all
    select 30, 1, 1 from dual
    

    【讨论】:

      【解决方案3】:

      快速一起输入,所以我不确定它是否正确。但我要做的是从用户 10 中选择新用户尚未拥有的所有产品 ID。

      您的问题中缺少的是 user_id 的来源。您可能希望将其与用户表连接起来,以便为所有用户运行它。

      insert into pricerules
         (user_id, prod_id, price)
         select &new_user_id
               ,prod_id
               ,price
           from pricerules p
          where user_id = 10
            and not exists (select 1
                   from pricerules p2
                  where p2.userid = &new_userid
                    and p2.prod_id = p.prod_id)
      

      【讨论】:

      • 我不想再把事情复杂化,但实际上用户表中有一个字段“belongs_to_user_id”。所以 new_user_id 将全部是 SELECT user_id FROM users WHERE belongs_to_user_id = 10。我的挣扎是完全相同的:我找不到如何为每个用户获取该 ID。所以我能够找到新用户没有的价格规则,但我不知道user_id。 :-s
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多