My schema 'test' has 3 tables: 'user', 'post' and 'revision'.
CREATE TABLE IF NOT EXISTS `test`.`user` (
`iduser` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`iduser`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `test`.`post` (
`idpost` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`iduser` INT UNSIGNED NOT NULL,
`content` VARCHAR(4000) NOT NULL,
`revision_count` INT NOT NULL DEFAULT 0,
PRIMARY KEY (`idpost`),
INDEX `fk_post_user1_idx` (`iduser` ASC),
CONSTRAINT `fk_post_user1`
FOREIGN KEY (`iduser`)
REFERENCES `test`.`user` (`iduser`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `test`.`revision` (
`idrevision` INT UNSIGNED NOT NULL,
`iduser` INT UNSIGNED NOT NULL,
`idpost` INT UNSIGNED NOT NULL,
`content` VARCHAR(4000) NOT NULL,
UNIQUE INDEX `index1` (`idpost` ASC, `idrevision` ASC),
PRIMARY KEY (`idrevision`, `iduser`),
INDEX `fk_revision_user1_idx` (`iduser` ASC),
CONSTRAINT `fk_revision_post`
FOREIGN KEY (`idpost`)
REFERENCES `test`.`post` (`idpost`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_revision_user1`
FOREIGN KEY (`iduser`)
REFERENCES `test`.`user` (`iduser`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
And there is the script creates data:
INSERT INTO `test`.`user` (`iduser`, `name`) VALUES (1, 'Ann');
INSERT INTO `test`.`user` (`iduser`, `name`) VALUES (2, 'Bob');
INSERT INTO `test`.`post` (`idpost`, `iduser`, `content`, `revision_count`) VALUES (1, 1, 'this is first post', 1);
INSERT INTO `test`.`revision` (`idrevision`, `iduser`, `idpost`, `content`) VALUES (1, 1, 1, 'this is old content of first post');
I create 2 sessions work concurrently. Session 1 works with query:
BEGIN;
INSERT INTO revision (idrevision, idpost, iduser, content) VALUES
((SELECT max_idrevision + 1
FROM (SELECT max(idrevision) AS max_idrevision
FROM revision WHERE idpost = 1) AS anon_1),
1, 2, 'abc xyz');
Now session 2 works:
BEGIN;
UPDATE revision SET idrevision=3 WHERE idpost=1 AND iduser =1;
-- will hang by lock
-- but with this update
UPDATE revision SET content='nwe asdfs' WHERE idpost=1 AND iduser=1;
-- not hang
I don't know what's lock mysql used with query insert in session 1? Is it row lock or table lock or anything else ? If it's row lock, why does second update query in session 2 not hang ?