如何在选择时不存在的MySQL中添加行

我创建了一个数据库表:

CREATE TABLE IF NOT EXISTS `highscores` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL DEFAULT '0',
  `vocation` varchar(255) NOT NULL,
  `kills` int(11) NOT NULL DEFAULT '0',
  `deaths` int(11) NOT NULL DEFAULT '0',
  `attempts` int(11) NOT NULL DEFAULT '0',
  `monster` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

现在我想使用 LUA 语言在该表中插入和更新数据:

function highscore(accID, monster, vocation)
print("ERROR HERE?")
local results = db.storeQuery("SELECT 'id' FROM 'highscores' WHERE 'account_id' = "..accID.." AND 'vocation' = "..vocation.." AND 'monster' = "..monster)
print("OR ERROR HERE?")
    if not results then
        db.query("INSERT INTO highscores('account_id', 'attempts', 'kills', 'deaths', 'vocation', 'monster') VALUES ("..accID..","..(0)..","..(0)..","..(0)..","..vocation..","..monster..")")
    end
print()

函数继续执行,但我已经遇到了问题。 我两次收到错误提示,一次是尝试 SELECT,另一次是尝试 INSERT。 它说我的语法与 MySQL 版本不匹配...

还尝试了这个,不过还是出现了同样的问题,语法错误:

db.query("INSERT INTO 'highscores'('account_id', 'vocation', 'kills', 'deaths', 'attempts', 'monster') SELECT * FROM (SELECT "..accID..","..vocation..","..(0)..","..(0)..","..(0)..","..monster.." WHERE NOT EXISTS ( SELECT 'account_id' FROM 'highscores' WHERE 'account_id' = "..accID.." AND 'vocation' = "..vocation.." AND 'monster' = "..monster..") LIMIT 1;")

即使我手动插入正确的值,它也应该自动插入。 然后我尝试选择它,却收到语法错误提示。

我在任何其他表中都没有这个问题。

点赞
用户1442917
用户1442917

我认为你引用的位置是错误的,应该改成:

([[SELECT id FROM highscores WHERE account_id = %s AND vocation = "%s" AND monster = "%s"]])
:format(accID, vocation, monster)

在你的情况下,你会写成 WHERE 'account_id' = 123 AND 'vocation' = something,而实际上应该是 WHERE account_id = 123 AND vocation = 'something'(假设 accID 只包含数字值)。

2015-05-19 22:18:28