I'd checked other similar kind of issues e.g. "deadlock in MySQL" in stack overflow but nothing leads to the solution.
REPLACE INTO db2.table2 (id, some_identifier_id, name, created_at, updated_at) (SELECT id, some_identifier_id, name, created_at, updated_at FROM db1.table1 WHERE some_identifier_id IS NOT NULL AND some_identifier_id NOT IN (SELECT some_identifier_id FROM db2.table1 WHERE some_other_identifier_id IS NOT NULL));
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
Situation:
- All the tables are InnoDB; db1.table1 => Collation: latin1_swedish_ci and for db2 => Collation: utf8_unicode_ci
- The query works fine in development server where version is Server version: 10.0.15-MariaDB
- Let's assume I have 5 DB servers which shares multi-master replication using Galera cluster.
- I'm executing the query manually in any of those 5 servers and getting the error.
- That server's version is same as the dev server where the query execution is successful i.e. 10.0.15-MariaDB
Tried:
- Included LOCK IN SHARE MODE e.g. REPLACE INTO... (1st select query (sub query) LOCK IN SHARE MODE); But it failed with the same message.
- Insert / REPLACE ... (1st select query (sub query LOCK IN SHARE MODE) LOCK IN SHARE MODE); it also failed with the same message.
- Tried with ordering by id in select query / sub select query. Again failed with same message.
- db1.table1 and db2.table1 both have almost only 50k records, so that shouldn't cause any issue I guess.
- All the tables have id as the primary key and auto increament. But I'm somehow using them explicitly- please observe the query.
- SHOW ENGINE INNODB STATUS; doesn't add up any useful hint to me.
The most probable reason could be due to multi-master replication behind the galera cluster for its optimistic locking (http://www.severalnines.com/blog/avoiding-deadlocks-galera-set-haproxy-single-node-writes-and-multi-node-reads). But that should not fail when executing the query on an individual node? Though on success I've to execute the same in that multi-master replication but I guess if the basic issue is solved then replicated servers won't create issue anymore.
Note:
I need to do this without any temp table or storing the sub query's result in code. There are some other dependencies for which executing a single query is the most favorable way till now.