2012-03-20 58 views
0

我有一張表,例如pricerules,爲顧客儲存特價物品。現在我想基於其他用戶同步這些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 ..

回答

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) ; 
+0

OP已經要求它基於用戶10的價格,所以也許你需要添加到subqry t1',其中user_id <> 10'和subqry t2'where user_id = 10' – 2012-03-20 14:12:41

+0

@ABCade謝謝!我錯過了。我已經更新了我的答案。 – 2012-03-20 14:32:21

+0

不幸的是,當您還需要使用序列(使用seq.nextval)插入主鍵時,此方法看起來效果不佳。序列總是會加1。 – rolandow 2012-04-26 12:12:20

0

我沒有在很長一段時間使用甲骨文,所以我的語法可能稍有偏差,但總體思路是:

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 
0

快速鍵入此所以我不確定它是否正確。但我想要做的是從用戶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) 
+0

我不想讓事情更復雜,但實際上在用戶表中有一個字段「belongs_to_user_id」。因此,new_user_id將全部是SELECT user_id FROM users whereERE_to_user_id = 10.我的掙扎是完全一樣的:我找不到如何爲每個用戶獲取該ID。所以我能夠找到新用戶沒有的價格規則,但我不知道user_id。 :-s – rolandow 2012-03-21 09:46:04

相關問題