It's not clear what's causing the deadlock. (Note that SQL operations involving MyISAM tables attempt to obtain exclusive locks on the entire table, so I'm assuming you are using InnoDB, or some other storage engine other than MyISAM.)
I'd avoid the correlated subquery in the SELECT list, and use a JOIN pattern instead. I believe that with a subquery in the SELECT list, MySQL will execute that subquery for every row returned in the outer query.
INSERT INTO db2.targetTable (id, value1, value2)
SELECT u.id
, t.value1
, t.value2
FROM db1.table t
LEFT
JOIN db2.User u
ON u.id = t.user
The subquery in your statement includes a LIMIT 1
clause. If that is needed because the id
column in the db2.User
table is not unique (which would be odd, but possible) then the query I gave above would need to include a GROUP BY <db1.table1 PRIMARY KEY>
, to avoid creating duplicate rows from a source row.
If the db1.table has a PRIMARY KEY of id
, then:
INSERT INTO db2.targetTable (id, value1, value2)
SELECT u.id
, t.value1
, t.value2
FROM db1.table t
LEFT
JOIN db2.User u
ON u.id = t.user
GROUP BY t.id