MySQL INSERT重复键UPDATE与SELECT

时间:2013-07-14 11:15:41

标签: mysql select on-duplicate-key

我有类似以下的查询

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

会引发以下错误

  

1093 - 您无法在FROM子句

中为更新指定目标表'connections'

显然我不能在insert into on duplicate update语法中使用SELECT子句,但我宁愿这样做,而不是运行2个查询。谁能告诉我怎么做到这一点?

3 个答案:

答案 0 :(得分:4)

请尝试这样:

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

此问题似乎是由于mysql 4.1.7版中的错误导致

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

请参阅Here

不确定这是否与您使用的版本相同。

答案 1 :(得分:1)

试试这个

    INSERT INTO connections (`c_id`,`in`,`out`,`ip`,`userID`) 
    SELECT c_id ,'1373799802', 0, INET_ATON('127.0.0.1'),4
    FROM connections 
    WHERE (a bunch of conditions) 
    ORDER BY c_id DESC LIMIT 1 

    ON DUPLICATE KEY UPDATE `out` = 1

答案 2 :(得分:1)

查询中的以下代码:

SELECT c_id 
FROM connections 
WHERE (a bunch of conditions) 
ORDER BY c_id DESC
LIMIT 1 

实际上会产生一个表而不是单个值。要成功尝试,请尝试以下方法:

INSERT INTO connections (`c_id`,`in`,`out`,`ip`,`userID`) 
    SELECT  c_id,
            '1373799802',
            0,
            INET_ATON('127.0.0.1'),
            4
    FROM connections 
    WHERE (a bunch of conditions) 
    ORDER BY c_id DESC LIMIT 1 
ON DUPLICATE KEY 
UPDATE `out` = 1