INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE mysql mysql

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE


MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,                 inact, inadur, inadist,                 smlct, smldur, smldist,                 larct, lardur, lardist,                 emptyct, emptydur)SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct,        t.inact, t.inadur, t.inadist,        t.smlct, t.smldur, t.smldist,        t.larct, t.lardur, t.lardist,        t.emptyct, t.emptydur FROM tmp t WHERE uid=xON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...


Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,                 inact, inadur, inadist,                 smlct, smldur, smldist,                 larct, lardur, lardist,                 emptyct, emptydur)SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct,        sb.inact, sb.inadur, sb.inadist,        sb.smlct, sb.smldur, sb.smldist,        sb.larct, sb.lardur, sb.lardist,        sb.emptyct, sb.emptydurFROM(SELECT id, uid, location, animal, starttime, endtime, entct,        inact, inadur, inadist,        smlct, smldur, smldist,        larct, lardur, lardist,        emptyct, emptydur FROM tmp WHERE uid=xGROUP BY location) as sbON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...


when SELECT statement has a GROUP BY clause.

    ....    ON DUPLICATE KEY UPDATE        larct=VALUES(larct), lardur=VALUES(lardur),lardist=     VALUES(lardist)