2013-01-10 87 views
1

我有這些SQL的指令:UPDATE,SUM SQL

CREATE TABLE discipline (
     did INT PRIMARY KEY, 
     code VARCHAR(127) UNIQUE, 
     university VARCHAR(127), 
     number_students INT 
) ENGINE=INNODB; 

CREATE TABLE precedence(
     type VARCHAR(127), 
     basic INT, 
     advanced INT, 
     PRIMARY KEY (basic, advanced), 
     FOREIGN KEY (basic) REFERENCES discipline(did) ON DELETE CASCADE ON UPDATE CASCADE, 
     FOREIGN KEY (advanced) REFERENCES discipline(did) 
)ENGINE=INNODB; 

INSERT INTO discipline VALUES (1,'BD','U1',30); 
INSERT INTO discipline VALUES (2,'IBD','U2',30); 
INSERT INTO discipline VALUES (3,'SIBD','U3',30); 
INSERT INTO precedence VALUES ('optional',1,2); 
INSERT INTO precedence VALUES ('mandatory',2,3); 
UPDATE discipline SET did=did+did WHERE did=2; 

我不理解爲什麼指令SELECT SUM (DISTINCT did)的結果是6,而不是8(1 + 4 + 3)。具有更新指令的值2(did)不應該是4?你能解釋一下嗎?謝謝。

+0

不應該預期的結果是** 8 **(1 + 3 + 4)而不是10?更新前的 – ppeterka

+0

1 + 2 + 3 = 6。更新後1 + 4 + 3 = 8。你期待什麼? –

+0

應該是8,它的工作對我來說至少在SQL SERVER – lante

回答

4

更新指令中的值2(做)不應該是4嗎?

不,它是4,它應該。

因爲SQL中的UPDATE語句,都是全部一次操作。這意味着,在同一個邏輯階段中,您擁有的所有表達式都將在同一時間點進行評估。在您的示例:

UPDATE discipline 
SET did = did + did 
WHERE did=2; 

因爲表達式did = did + did被同時評價機智的值did = 2did將等於4

SQL Fiddle Demo

這會讓你的表如下所示:

| DID | CODE | UNIVERSITY | NUMBER_STUDENTS | 
--------------------------------------------- 
| 1 | BD |   U1 |    30 | 
| 3 | SIBD |   U3 |    30 | 
| 4 | IBD |   U2 |    30 | <<<<< 

我不明白爲什麼指令SELECT SUM (DISTINCT那樣)的結果是6和不是9(1 + 4 + 3)。

更新後的Did值將是:

1 
3 
4 

因此:

SELECT SUM(DISTINCT did) 
FROM discipline 

將等於8

SQL Fiddle Demo


在更新後的例子,你將無法UPDATE did,監守外鍵約束,你會得到一個例外:

不能刪除或更新父行:外鍵約束失敗 (db_2_65e0cprecedence,約束precedence_ibfk_2 FOREIGN KEY (advanced)參考文獻disciplinedid))

SQL Fiddle Demo

在這種情況下,你需要將ON DELETE CASCADE ON UPDATE CASCADE添加到其他的外鍵約束:

FOREIGN KEY (advanced) REFERENCES discipline(did) 

然後UPDATE

UPDATE discipline 
SET did=did + did 
WHERE did=2; 

會像以前一樣解釋,並

SELECT SUM(DISTINCT did) 
FROM discipline 

將等於8

SQL fiddle demo of the two table(working)

+0

而隨着表的優先級,數值會改變嗎?謝謝。 – tomss

+0

@ user1966757對不起,你這是什麼意思? –

+0

我已編輯我的帖子我正在使用名爲優先級的表,我沒有把它放在我的文章上。這會改變結果嗎? – tomss

0

正確的結果應該是8,因爲在更新後,這三個值是:(1,4,3),以使子值爲8