用于数据迁移的SQL查询

时间:2013-03-26 16:02:49

标签: sql oracle11g

我有一张桌子。

CREATE TABLE StockItem
(
    id        NUMBER(8) NOT NULL,
    book_id   NUMBER(8) NOT NULL,
    wh_id     NUMBER(8) NOT NULL,
    quantity  NUMBER(4) NOT NULL,
    price     NUMBER(8,2) NOT NULL
);

ALTER TABLE StockItem
    ADD CONSTRAINT UQ_StockItem UNIQUE (book_id, wh_id);
ALTER TABLE StockItem ADD CONSTRAINT PK_StockItem 
    PRIMARY KEY (id);
ALTER TABLE StockItem ADD CONSTRAINT FK_StockItem_Book 
    FOREIGN KEY (book_id) REFERENCES Book (id);
ALTER TABLE StockItem ADD CONSTRAINT FK_StockItem_Warehouse 
    FOREIGN KEY (wh_id) REFERENCES Warehouse (id);

现在假设wh_id = 1已关闭,我应将所有图书移至wh_id = 2wh_id = 2的图书价格应与wh_id = 1中的图书价格相同,并且quantity的图书应该正确计算(例如,对于两个房屋的book_id增加)。我怎么能这样做?

UPD:

以下是我如何获取图书的新数量值。

SELECT BOOK_ID, SUM(QUANTITY) 
FROM STOCKITEM
WHERE WH_ID IN (1, 2)
GROUP BY BOOK_ID;

现在我应该以某种方式更新它们。

UPDATE STOCKITEM
SET QUANTITY = /* My summed quantity */
WHERE BOOK_ID = /* Book ids from 1 and 2 wh */

3 个答案:

答案 0 :(得分:1)

UPDATE (SELECT SI2.quantity AS qty2, SI2.price as p2, SI1.quantity as qty1, SISI1.price as p1
        FROM   StockItem SI2 INNER JOIN StockItem SI1 
        ON     (SI2.book_id = SI1.book_id)
        WHERE  SI2.wh_id = 2 AND SI1.wh_id = 1) WH
SET WH.qty2 = WH.qty2 + WH.qty1,
    WH.p2 = WH.p1

此答案基于Update statement with inner join on Oracle,它要求Oracle接受WH作为可更新。我无法测试。

答案 1 :(得分:1)

我认为您应该使用INNER JOIN声明SELECT进行UPDATE stockItem INNER JOIN (SELECT book_id, SUM(quantity) AS total FROM stockItem WHERE wh_id IN (1, 2) GROUP BY book_id) AS qntyBooks ON qntyBooks.book_id = stockItem.book_id SET stockItem.quantity = qntyBooks.total, stockItem.wh_id = 2; -- all wh_id in 1, 2 will change to 2

{{1}}

我在MySQL上测试过(我认为可能与Oracle11g相同)并且工作方式如下:

更新前:

 ---- --------- ------- ---------- ------- 
| id | book_id | wh_id | quantity | price |
 ---- --------- ------- ---------- ------- 
|  1 |       1 |     1 |        3 |    10 |
|  2 |       2 |     1 |        3 |    20 |
|  3 |       3 |     1 |        3 |    30 |
|  4 |       1 |     2 |        2 |    40 |
|  5 |       2 |     2 |        2 |    50 |
 ---- --------- ------- ---------- ------- 

更新后:

 ---- --------- ------- ---------- ------- 
| id | book_id | wh_id | quantity | price |
 ---- --------- ------- ---------- ------- 
|  1 |       1 |     2 |        5 |    10 |
|  2 |       2 |     2 |        5 |    20 |
|  3 |       3 |     2 |        3 |    30 |
|  4 |       1 |     2 |        5 |    40 |
|  5 |       2 |     2 |        5 |    50 |
 ---- --------- ------- ---------- ------- 

我希望这是你想要的。祝你好运!

答案 2 :(得分:1)

使用您当前的数据库设计,您不能。原因是CONSTRAINT UQ_StockItem UNIQUE(book_id,wh_id)。

如果仓库1中的price_id = 1,价格= $ 1.00,仓库2中的book_id = 1,价格= $ 1.05,则此约束将阻止您将图书从一个仓库移动到另一个仓库,同时保持原始价格。 / p>

需要付出一些代价。