5

我有如下查询

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 子句中为更新指定目标表“连接”

显然,我不能在insert into on duplicate update语法中包含 SELECT 子句,但我真的宁愿这样做,而不是运行 2 个查询。谁能告诉我我该怎么做?

4

3 回答 3

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

这里

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

于 2013-07-14T11:28:40.057 回答
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
于 2013-07-14T11:24:48.130 回答
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
于 2013-07-14T11:24:55.103 回答