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

时间:2015-05-19 21:27:46

标签: mysql sql-server lua

我创建了数据库表:

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;")

即使我手动插入正确的值,它也应自动插入。 然后我尝试选择它,它给我语法错误。

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

1 个答案:

答案 0 :(得分:0)

我认为你的报价是错误的;而不是

([[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(假设{{1}}只有数字值。)