嘿,我正在使用这样的查询:
INSERT INTO likes(
likes_memory_id,
likes_comment_id,
likes_owner_id,
likes_like
) VALUES (
:likes_memory_id,
:likes_comment_id,
:likes_owner_id,
:likes_like)
当用户单击“赞”按钮时,此查询会添加一个新行。所以这个查询允许喜欢多次。为了防止这种情况,我可以使用一个select语句,我可能会在两个查询中成功,但我认为有一个更好的方法来做到这一点。 (我研究过如果不存在声明,但我不太了解)我如何避免多重喜欢?
答案 0 :(得分:2)
最简单的方法是在列上创建一个您想要唯一的唯一索引;
CREATE UNIQUE INDEX uq_mem_own ON likes(
likes_memory_id, likes_owner_id
);
...并使用INSERT IGNORE插入喜欢的内容,如果索引没有阻止它将插入值,否则只是忽略它;
INSERT IGNORE INTO likes(
likes_memory_id,
likes_owner_id,
likes_like
) VALUES (
:likes_memory_id,
:likes_owner_id,
:likes_like)
答案 1 :(得分:1)
INSERT INTO likes(
likes_memory_id,
likes_comment_id,
likes_owner_id,
likes_like
SELECT *
FROM (:likes_memory_id, :likes_comment_id, :likes_owner_id ,:likes_like) tmp
WHERE NOT EXISTS ( SELECT *
FROM `likes`
WHERE `likes_memory_id` = :likes_memory_id
AND `likes_comment_id` = :likes_comment_id
AND `likes_owner_id` = :likes_owner_id
AND `likes_like` = :likes_like
) LIMIT 1;
答案 2 :(得分:0)
You can accomplish this either disable like button after hit or
using the following query
INSERT INTO likes
(likes_memory_id,
likes_comment_id,
likes_owner_id,
likes_like)
SELECT t1.likes_owner_id
FROM likes t1
WHERE NOT EXISTS(SELECT likes_owner_id
FROM likes t2
WHERE t2.likes_owner_id = t1.likes_owner_id);
and make sure that your likes_owner_id is primary or a unique key
答案 3 :(得分:-1)
好问题!您可以简单地收集用户的IP地址,如果该用户尝试“喜欢”两次,则不会记录。
步骤1:创建一个名为IP(或任何你喜欢的)的新列[这将用于收集用户IP地址。)
步骤2:将IP设置为PRIMARY KEY(这是防止重复输入的内容)
第3步:将其添加到您的查询中。
INSERT INTO likes(
IP,
likes_memory_id,
likes_comment_id,
likes_owner_id,
likes_like
) VALUES (
:IP,
:likes_memory_id,
:likes_comment_id,
:likes_owner_id,
:likes_like)
步骤4:现在您要做的就是添加一行代码来收集用户IP并将其与其他信息一起提交。