UPDATE `comment`
SET `agree`=`agree`+1,(INSERT INTO `reacted_on` VALUES (10,197))
WHERE `id`=197 and 0 = (SELECT COUNT(*) FROM `reacted_on` WHERE `id_user`=10 and `id_comment`=197)
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
'(INSERT INTO `reacted_on` VALUES (10,197)) WHERE `id`=197 and 0 = (SELECT COUNT(' at line 1
我想在
agree
中修改comment
,但我想防止同一用户对一条评论的同意超过一条。因此,首先我检查用户是否对同一条评论做出了反应;我递增agree。然后我插入一行以防止用户对同一条评论做出反应。我错过了什么?为什么不是真的?
我该怎么做才能解决这个问题?
如何在更新查询中使用INSERT语句?
这就是我使用查询的地方:
$con = mysql_connect($my_sql_servername,$my_sql_username,$my_sql_password);
mysql_select_db($my_sql_database, $con);
if($validation != $_SESSION['validation'])
die('-1');
$sql = "IF NOT EXISTS (SELECT * FROM `reacted_on` WHERE `id_user`=".$id_user." and `id_comment`=".$id_comment." ) THEN INSERT INTO `reacted_on` VALUES (10,197); UPDATE `comment` SET `agree`=`agree`+1 WHERE `id`=".$id_comment." END IF;";
//echo $sql;
if(!mysql_query($sql)){die(mysql_error());}
最佳答案
基本上,可能是这样的:
IF NOT EXISTS (
SELECT *
FROM `reacted_on`
WHERE `id_user`=10 and `id_comment`=197
)
THEN
INSERT INTO `reacted_on` VALUES (10,197);
UPDATE `comment`
SET `agree`=`agree`+1
WHERE `id`=197;
END IF;
您必须使用单独的语句来实现这一点,但您可以将它们包装成一条
IF
指令。编辑
检查行的存在的另一种方法是使用
SELECT COUNT(*)...
(就像您在尝试脚本中所做的那样)。因此,上述查询的开头将更改为:IF 0 = (
SELECT COUNT(*)
FROM `reacted_on`
WHERE `id_user`=10 and `id_comment`=197
)
THEN
... /* same as above */