Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INSERT on duplicate key UPDATE with SELECT

I have a query like the following

INSERT INTO connections (`c_id`,`in`,`out`,`ip`,`userID`) 
VALUES ( 
    ( 
        SELECT c_id 
        FROM connections 
        WHERE (a bunch of conditions) 
        ORDER BY c_id DESC LIMIT 1 

    ),
    '1373799802',
    0,
    INET_ATON('127.0.0.1'),
    4

) 
ON DUPLICATE KEY UPDATE `out` = 1

Which throws the following error

1093 - You can't specify target table 'connections' for update in FROM clause

Obviously I can't have a SELECT clause within the insert into on duplicate update syntax, but I'd really rather do that instead of have 2 queries running. Can anyone tell me how I can do this?

like image 808
php_nub_qq Avatar asked Jul 14 '13 11:07

php_nub_qq


People also ask

How do I use insert on duplicate key update?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.

How does on duplicate key update work?

ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas. The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.

How do I insert without duplicates in MySQL?

Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

How do I Upsert in MySQL?

We can perform MySQL UPSERT operation mainly in three ways, which are as follows: UPSERT using INSERT IGNORE. UPSERT using REPLACE. UPSERT using INSERT ON DUPLICATE KEY UPDATE.


1 Answers

Try like this instead:

INSERT INTO connections (`c_id`,`in`,`out`,`ip`,`userID`) 
VALUES ( 
    ( 
SELECT p.c_id 
        FROM (select * from connections) p 
        WHERE (a bunch of conditions) 
        ORDER BY p.c_id DESC LIMIT 1 

    ),
    '1373799802',
    0,
    INET_ATON('127.0.0.1'),
    4

) 
ON DUPLICATE KEY UPDATE `out` = 1

This issue seems due to a bug in mysql version 4.1.7 which states that

you can't update the same table which you use in the SELECT part

see Here

Not sure if this is the same version you are using as well.

like image 119
Rahul Avatar answered Sep 28 '22 14:09

Rahul