I have these SQL instructions:
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;
I don’t understand why the result of the instruction SELECT SUM (DISTINCT did) is 6 and isn’t 8 (1+4+3). The value 2 (did) with the update instruction shouldn’t be 4? Can you explain this to me? Thanks.
No, it is 4, and it should.
Because the
UPDATEstatements in SQL, are All-at-once operations. Meaning that all the expressions that you have, in the same logical phase are evaluated as if at the same point in time. In your example:the
didwill equal to4because the expressiondid = did + didis evaluated wit the valuedid = 2at the same time.SQL Fiddle Demo
This will make your table looks like:
The values of
Didafter update will be:Therefore:
Will equal to
8.SQL Fiddle Demo
In your updated example, you won’t be able to
UPDATE did, becuase of the foreign key constraint and you will got an exception:SQL Fiddle Demo
In this case, you will need to add the
ON DELETE CASCADE ON UPDATE CASCADEto the other foreign key constraint:Then the
UPDATE:will be the same as explained before, and
Will equal to
8.SQL fiddle demo of the two table(working)