更新,SUM sql

时间:2013-01-10 13:04:20

标签: mysql sql

我有这些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(已做)不应该是4?你能解释一下吗?感谢。

2 个答案:

答案 0 :(得分:4)

  

更新指令的值2(did)不应该是4?

不,它是4,它应该。

因为SQL中的UPDATE语句是 All-at-once 操作。这意味着您在同一逻辑阶段中拥有的所有表达式都被评估为在同一时间点。在您的示例中:

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

did将等于4,因为同时使用值did = did + did评估表达式did = 2

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,CONSTRAINT 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)

答案 1 :(得分:0)

正确的结果应为8,因为更新后,三个值为(1,4,3),因此子值为8.