是否可以检查表中的num行是否为0然后执行插入,所有这些都在一个sql语句中?
这是我尝试的查询,但它说我有语法错误:
$query =
"IF (SELECT COUNT(ID) FROM votes WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0
INSERT INTO votes (itemtype, itemid, userid) VALUES (1, $itemid, $userid)
SELECT 1 AS result
ELSE
SELECT 0 AS result
END IF";
我知道SELECT COUNT位可以自己成功运行。
答案 0 :(得分:1)
没有想法,如果这是解决这个问题的最佳方法,但它会奏效。基本上,如果条件为false,它只会导致错误,因此它会阻止插入:
-- make itemtype not nullable then simply insert
INSERT INTO votes SELECT
CASE
WHEN
(SELECT COUNT(ID)
FROM votes
WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0 THEN 1
ELSE NULL
END CASE,
$itemid, $userid;
答案 1 :(得分:0)
我现在无法访问MySQL来测试它,但这会有效吗?
INSERT INTO votes (itemtype, itemid, userid)
(SELECT 1,$itemid, $userid
WHERE NOT EXISTS (
SELECT *
FROM votes
WHERE itemtype=1
AND itemid=$itemid
AND userid=$userid))