更好的写入更新方式

时间:2017-09-26 13:12:08

标签: sql oracle

我在这里要做的是对所有成员memberID更新limit_ by 2。有没有更好的方法将更新写入一个查询?喜欢组合它们而不是多次查询?我建议哪个运营商使用它们将它们组合成一个查询。

这是我的代码:

CREATE TABLE Member
(memberID INT,
lastname varchar (20),
firstname varchar (20),
address varchar(20),
phone_number INT,   
limit_ INT,
PRIMARY KEY (memberID));    

INSERT INTO Member VALUES (001, 'Lee', 'Nancy', 'Brownlea Drive', 1254896325, 1);
INSERT INTO Member VALUES (002, 'Le', 'Ray', '10th Street', 1234561256, 2);
INSERT INTO Member VALUES (003, 'Kan', 'Charlie', '5th Street', 1234567236, 4);
INSERT INTO Member VALUES (004, 'Brown', 'Joe', 'Elm Street', 1234567845, 8);
INSERT INTO Member VALUES (005, 'Smith', 'John', '33 East', 1234567890, 3);
INSERT INTO Member VALUES (006, 'Khang', 'Nkaujyi', '358 Spencer', 2145345625, 5);
INSERT INTO Member VALUES (007, 'Jones', 'David', '4th Street', 14812365789, 7);

以下是查询:

UPDATE Member    SET limit_ = 3    WHERE memberID = 1;
UPDATE Member    SET limit_ = 4    WHERE memberID = 2;
UPDATE Member    SET limit_ = 6    WHERE memberID = 3;
UPDATE Member    SET limit_ = 10    WHERE memberID = 4;
UPDATE Member    SET limit_ = 5    WHERE memberID = 5;
UPDATE Member    SET limit_ = 7    WHERE memberID = 6;
UPDATE Member    SET limit_ = 9    WHERE memberID = 7;

2 个答案:

答案 0 :(得分:2)

您可以在SET子句中执行数学运算...如果您想将所有LIMIT_增加+2,请执行以下操作:

UPDATE member
SET LIMIT_ = LIMIT_ + 2

答案 1 :(得分:1)

如果要在不遵循任何数学逻辑的情况下增加某些数字的限制,那么您可以使用它。

UPDATE Member SET limit_ =     
CASE  WHEN memberID = 7 THEN 9   
      WHEN memberID = 6 THEN 7  
      WHEN memberID = 5 THEN 5     
      WHEN memberID = 4 THEN 10     
      WHEN memberID = 3 THEN 6     
      WHEN memberID = 2 THEN 4     
      WHEN memberID = 1 THEN 3 
ELSE limit_
END

正如在评论中正确指出的那样,当使用数学逻辑(比如将所有限制增加2)时,另一种选择(更好的方式)

UPDATE Member 
SET limit_ = limit_ + 2
WHERE memberID between 1 and 7;