简体   繁体   中英

InnoDB Foreign Keys and Commit

I'm converting an existing database from MyISAM to InnoDB and implementing various foreign keys, I'm having an issue with running the convert script on my database though:-

I'm running all queries as below

DELETE FROM example WHERE user NOT IN (select id FROM users);
ALTER TABLE `example` CHANGE `user` `user` INT( 11 ) UNSIGNED NOT NULL ;
ALTER TABLE example ADD FOREIGN KEY (user) REFERENCES users(ID);
ALTER TABLE example ADD FOREIGN KEY (car) REFERENCES cars(ID);

When I run all queries it fails due to a foreign key constraint, due to the fact the DELETE statement hasn't run - if I run them individually, it's fine - is it an issue with commit on the innodb database or is it due to speed of the delete not completing before the next query?

Is it also ok to have two foreignkeys of ID? (two different tables users.id and cars.id).

Thanks!

No idea of what the error message might say or what you're trying to accomplish but ALTER TABLE is a DDL statement and those cannot be rollbacked in MySQL. The Statements That Cause an Implicit Commi manual chapter explains:

The statements listed in this section (and any synonyms for them) implicitly end any transaction active in the current session, as if you had done a COMMIT before executing the statement . As of MySQL 5.5.3, most of these statements also cause an implicit commit after executing;

[...]

Data definition language (DDL) statements that define or modify database objects

[...]

ALTER TABLE , CREATE TABLE , and DROP TABLE do not commit a transaction if the TEMPORARY keyword is used. (This does not apply to other operations on temporary tables such as CREATE INDEX , which do cause a commit.) However, although no implicit commit occurs, neither can the statement be rolled back. Therefore, use of such statements will violate transaction atomicity: For example, if you use CREATE TEMPORARY TABLE and then roll back the transaction, the table remains in existence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM