【问题标题】:SQL syntax error on ON DUPLICATE KEY UPDATEON DUPLICATE KEY UPDATE 上的 SQL 语法错误
【发布时间】:2014-10-18 15:57:48
【问题描述】:

我有这张表,我想用一个当前使用 ON DUPLICATE KEY UPDATE 的语句来更新/插入:

index (INT) user(INT) entryId(INT) tags(text)
1              1          111      ||bla||
2              1          111      ||bla||
3              1          111      ||bla||

INSERT INTO 过滤器(索引、用户、entryId、标签)值 (1,1,'100003817186741',"||test1||||test2||"), (3,1,'100003021196089',"||test1||||test2||") 重复密钥更新 user=VALUES(user),entryId=VALUES(entryId),tags=VALUES(tags)

为什么会因为 SQL 语法错误而失败?

【问题讨论】:

    标签: php mysql sql database web-deployment


    【解决方案1】:

    index是一个SQL保留字,你必须重写你的查询

    INSERT INTO filters (`index`,`user`,entryId,tags) VALUES (1,1,'100003817186741',"||test1||||test2||"), (3,1,'100003021196089',"||test1||||test2||") ON DUPLICATE KEY UPDATE `user`=VALUES(`user`),entryId=VALUES(entryId),tags=VALUES(tags)
    

    【讨论】:

    【解决方案2】:

    因为index 是 MySQL 保留字而失败。

    http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

    要么用反引号括起来,要么为它选择另一个词

    INSERT INTO filters (index,user,entryId,tags)
                         ^    ^
    

    INSERT INTO filters (`index`,user,entryId,tags)
    

    【讨论】:

    • 用户也保留字
    • @DmitryBezik user 不是保留字,但use 是。
    • 是的,用户不是保留字
    • @Tzvi 嗨,只是一个简短的说明,看看你是否可以勾选复选标记以关闭问题,干杯。
    【解决方案3】:

    你的语法看起来很奇怪,四个竖线在一起,单引号和双引号混合在一起。

    INSERT INTO filters(index, user, entryId, tags)
        VALUES (1, 1, '100003817186741', "||test1||||test2|| "),  
               (3, 1, '100003021196089', "||test1||||test2|| ")
        ON DUPLICATE KEY UPDATE user=VALUES(user),entryId=VALUES(entryId),tags=VALUES(tags);
    

    我会这样写:

    INSERT INTO filters(`index`, `user`, entryId, tags)
        SELECT 1, 1, '100003817186741', CONCAT('||', test1, '||', test2) UNION ALL
        SELECT 3, 1, '100003021196089', CONCAT('||', test1, '||', test2)
        ON DUPLICATE KEY UPDATE `user` = VALUES(`user`),
                                entryId = VALUES(entryId),
                                tags = VALUES(tags);
    

    也就是说,使用显式的concat() 函数。使用select 代替values 只是个人喜好——select . . . union all 可以完成values 的所有功能等等。

    此外,请避免使用保留字(例如 index)作为列名或表名。这些是保留字,没有转义字符的 SQL 可读性更高。

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2018-06-27
      • 2011-05-16
      • 1970-01-01
      相关资源
      最近更新 更多