用if语句和case更新Mysql脚本

时间:2014-06-06 22:25:50

标签: mysql

为什么我不能使用或为什么会遇到错误。我正在尝试使用如下所示的脚本。我是一个新手,当涉及到mysql,我尝试创建这样的脚本,但我得到的错误如下

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 THEN dogs.dogcount = dogcount - dogdetails.total, dogdetails.statu' at line 4 

这是我的剧本

UPDATE dogs 
LEFT JOIN dogdetails ON dogs.username = dogdetails.username 
SET dogs.dogcount = 
CASE WHEN dogdetails.dogcount IS NOT 1 THEN dogs.dogcount = dogcount -    dogdetails.total, dogdetails.status = 'Checked'
WHEN dogdetails.dogcount = 1 THEN dogs.pto = pto - dogdetails.total, dogdetails.status = 'Checked'
WHERE dogdetails.id=4

我有什么遗漏或忽略了吗?

1 个答案:

答案 0 :(得分:1)

请记住,您必须使用关键字' end'在你的case语句之后并且总是返回一个值。比较数字时,IS NOT关键字也不正确。这是您的查询版本应该有效:

UPDATE dogs 
LEFT JOIN dogdetails ON dogs.username = dogdetails.username 
SET dogs.dogcount = CASE WHEN dogdetails.dogcount != 1 THEN dogs.dogcount = dogcount-dogdetails.total else dogs.dogcount end, 
dogs.pto= case WHEN dogdetails.dogcount = 1 THEN  pto - dogdetails.total else pto end,     
dogdetails.status = 'Checked'
WHERE dogdetails.id=4