我有一个类似以下的查询

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

哪个抛出以下错误



显然,我在insert into on duplicate update语法中没有SELECT子句,但我确实希望这样做,而不是运行2个查询。谁能告诉我我该怎么做?

最佳答案

尝试像这样:

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

不知道这是否与您使用的版本相同。

09-25 16:31
查看更多